React-redux Mapstatetoprops,mapdispatchtoprops How to use

Source: Internet
Author: User


Use react-redux
First, in the outermost container, wrap everything in the Provider component and pass the previously created store as a prop to the Provider .

Const App = () => {
  Return (
    <Provider store={store}>
      <Comp/>
    </Provider>
  )
};
Any component in the Provider (such as Comp here), if you need to use the data in the state, you must be a "connected" component - use the connect method to wrap the "component you wrote ( MyComp )" product.

Class MyComp extends Component {
  // content...
}

Const Comp = connect(...args)(MyComp);
As you can see, the connect method is the most important.

Connect Detailed
Let's take a look at what the connect method does.

First look at the signature of the function:

Connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

Connect() receives four parameters, namely mapStateToProps , mapDispatchToProps , mergeProps and options .

mapStateToProps(state, ownProps) : stateProps
This function allows us to bind the data in the store as a props to the component.

Const mapStateToProps = (state) => {
  Return {
    Count: state.count
  }
}
The first argument to this function is the store of Redux , from which we extracted the count property. Because the object with the count property is returned, MyComp will have a props field named count.

Class MyComp extends Component {
  Render(){
    Return <div> count: {this.props.count} times</div>
  }
}

Const Comp = connect(...args)(MyComp);
Of course, you don't have to pass the data in state to the component as it is, you can dynamically output the (minimum) properties the component needs based on the data in state.

Const mapStateToProps = (state) => {
  Return {
    greaterThanFive: state.count > 5
  }
}
The second parameter of the function, ownProps , is MyComp's own props . Sometimes, ownProps will also affect it. For example, when you maintain a list of users in the store, your component MyComp only cares about one user (reflected by userId in props).

Const mapStateToProps = (state, ownProps) => {
  // state is {userList: [{id: 0, name: ‘wang 2’}]}
  Return {
    User: _.find(state.userList, {id: ownProps.userId})
  }
}

Class MyComp extends Component {
  
  Static PropTypes = {
    userId: PropTypes.string.isRequired,
    User: PropTypes.object
  };
  
  Render(){
    Return <div>username: {this.props.user.name}</div>
  }
}

Const Comp = connect(mapStateToProps)(MyComp);
When state changes, or ownProps changes, mapStateToProps is called, and a new stateProps is evaluated, which is updated to MyComp after (with ownProps merge).

This is the basic way to connect data from the Redux store to components.

mapDispatchToProps(dispatch, ownProps): dispatchProps
The second argument to connect is mapDispatchToProps , which has the function of binding action as props to MyComp .

Const mapDispatchToProps = (dispatch, ownProps) => {
  Return {
    Increase: (...args) => dispatch(actions.increase(...args)),
    Decrease: (...args) => dispatch(actions.decrease(...args))
  }
}

Class MyComp extends Component {
  Render(){
    Const {count, increase, decrease} = this.props;
    Return (<div>
      <div> count: {this.props.count} times</div>
      <button onClick={increase}>Add</button>
      <button onClick={decrease}>decrease</button>
    </div>)
  }
}

Const Comp = connect(mapStateToProps, mapDispatchToProps)(MyComp);
Since the mapDispatchToProps method returns an object with an increase property and a decrease property, these two properties also become props for MyComp .

As shown above, calling actions.increase() only gets an action object {type:‘INCREASE‘} . To trigger this action, the dispatch method must be called on the store. Diapatch is the first argument to mapDispatchToProps. However, in order not to let the MyComp component perceive the existence of dispatch , we need to wrap the two functions of increase and decrease to make them directly callable (that is, calling this method will trigger dispatch ).

Redux itself provides the bindActionCreators function to wrap the action as a function that can be called directly.

Import {bindActionCreators} from ‘redux‘;

Const mapDispatchToProps = (dispatch, ownProps) => {
  Return bindActionCreators({
    Increase: action.increase,
    Decrease: action.decrease
  });
}
Similarly, when ownProps changes, the function is also called, generating a new dispatchProps , which (after statePrope and ownProps merge ) is updated to MyComp . Note that changes to action do not cause the above process, and the default action is fixed during the life of the component.

[mergeProps(stateProps, dispatchProps, ownProps): props]
As mentioned before, both stateProps and dispatchProps need to be assigned to MyComp after being merged with ownProps . The third argument to connect is used to do this. Normally, you can pass this parameter, and connect will use Object.assign instead of this method.

other
Finally, there is an options option, which is relatively simple and basically not used (especially when you follow some other "best practices" of React), this article skips. Students who want to know can look directly at the document. 
Reprinted from: https://www.tuicool.com/articles/MrmYN36




React-redux Mapstatetoprops,mapdispatchtoprops How to use


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.