Entry file index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

import { Provider } from 'react-redux'
import store from './store'
const Abc = (
  <Provider store={store}>
    <App />
  </Provider>
)

ReactDOM.render(Abc, document.getElementById('root'))
Copy the code

App Component (stateless component)Can also be a class extends Component of Class XXX, but it’s written differently.

import React from 'react'

import { connect } from 'react-redux'

const App = (props) = > {
  let { list, clickBtn, aa, inputChange } = props
  return (
    <div>
      <div>
        <input value={aa} onChange={inputChange} />
        <button onClick={clickBtn}>submit</button>
      </div>
      <ul>
        {list.map((item, index) => {
          return <li key={index}>{item}</li>
        })}
      </ul>
    </div>)}const stateToProps = (state) = > {
  return {
    aa: state.inputValue,
    list: state.list
  }
}

const dispatchToProps = (dispatch) = > {
  return {
    inputChange(e) {
      let action = {
        type: 'change_input'.value: e.target.value
      }
      dispatch(action)
    },
    clickBtn() {
      let action = {
        type: 'add_item'
      }
      dispatch(action)
    }
  }
}

export default connect(stateToProps, dispatchToProps)(App)
Copy the code

App-like components

import React, { Component } from 'react'

import { connect } from 'react-redux'
class App extends Component {
  render() {
    let { list, clickBtn, aa, inputChange } = this.props
    return (
      <div>
        <div>
          <input value={aa} onChange={inputChange} />
          <button onClick={clickBtn}>submit</button>
        </div>
        <ul>
          {list.map((item, index) => {
            return <li key={index}>{item}</li>
          })}
        </ul>
      </div>)}}const stateToProps = (state) = > {
  return {
    aa: state.inputValue,
    list: state.list
  }
}

const dispatchToProps = (dispatch) = > {
  return {
    inputChange(e) {
      let action = {
        type: 'change_input'.value: e.target.value
      }
      dispatch(action)
    },
    clickBtn() {
      let action = {
        type: 'add_item'
      }
      dispatch(action)
    }
  }
}

export default connect(stateToProps, dispatchToProps)(App)

Copy the code

store/index.js

import { createStore } from 'redux'
import reducer from './reducer'

const store = createStore(reducer)

export default store


Copy the code

store/reducer.js

const defaultState = {
  inputValue: 'ja131v22ab'.list: []}const reducer = (state = defaultState, action) = > {
  if (action.type === 'change_input') {
    let newState = JSON.parse(JSON.stringify(state))
    newState.inputValue = action.value
    return newState
  }

  if (action.type === 'add_item') {
    let newState = JSON.parse(JSON.stringify(state))
    newState.list.push(newState.inputValue)
    newState.inputValue = ' '
    return newState
  }

  return state
}
export default reducer


Copy the code