1. In the app. In js

    import { Provider } from "react-redux";

    Uniformly mounted on the outermost layer of the root component. There will only be one store(created by yourself)

    <Provider store={store}>
      <ComA/>
      <ComB/>
    </Provider>
    Copy the code
  2. Store/index.js

    As a repository for storing data

    // Import the reduex method
    import { createStore } from 'redux'; 
    // Import the reducer you created
    import {reducer} from '.. /reducer/index'
    / / build a store
    const store = createStore(reducer)
    
    export default store;
    Copy the code
  3. reducer/index.js

    Data was processed by reducer

    const reducer = (state={count: 0}, action) = > {
      const count = state.count
      switch (action.type) {
        case 'increase':
          return { count: count + 1 }
        case 'init':
          return { count: 0 }
        default:
          return state
      }
    }
    module.exports = {reducer}
    Copy the code

    Reduce can also be split and merged using combineReducers

    import { combineReducers } from 'redux';
    const reducerA = (state={count: 0}, action) = > {
     const count = state.count
     switch (action.type) {
       case 'increase':
         return { count: count + 1 }
       default:
         return state
     }
    }
    const reducerB = (state={count: 0}, action) = > {
     const count = state.count
     switch (action.type) {
       case 'init':
         return { count: 0 }
       default:
         return state
     }
    }
    // Merge multiple reducers
    const rootReducer = combineReducers({reducerA,reducerB});
    export default rootReducer;
    Copy the code
  4. Transfer the data action in the component

    The second parameter of connect, mapDispatchToProps, is used to send modified data

    import { connect } from 'react-redux';
    class ComA extends Component {... }// Send the data message
    const mapDispatchToProps = dispatch= > {
      return {
        sendAction: () = >{ // (in fact, the file sent to step [3] above is processed)
          dispatch({
            type: 'increase'})}}}/** * connect(receive data fn, send data FN)(component) */
    export default connect(null, mapDispatchToProps)(ComA)
    Copy the code
  5. Accept data state in the component

    The first parameter of connect, mapStateToProps, receives data

    
    import { Component } from "react";
    import { connect } from 'react-redux';
    
    class ComB extends Component {
      render() {
        return(
          // (props = this.props); // (props = this.props)
          <div>{this.props.XXX}</div>)}}// Accept data information
    const mapStateToProps = (state) = > {
      return {
        XXX: state.count
      }
    }
    /** * connect(receive data fn, send data FN)(component) */
    export default connect(mapStateToProps, null)(ComB)
    Copy the code