简体   繁体   中英

How to access properties added by mapStateToProps in mapDispatchToProps?

React Redux provides function connect to bind Redux state and dispatch to React component (as properties).

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

mapStateToProps(state, [ownProps]): stateProps

mapDispatchToProps(dispatch, [ownProps]): dispatchProps

How to access properties added by function mapStateToProps in function mapDispatchToProps ?

For example, I use function mapStateToProps to add property propertyFromState to the component, how to access property propertyFromState in function mapDispatchToProps ?

I try to use parameter ownProps to access it, but it is undefined .

You cannot access props in mapDispatchToProps. instead you can pass an argument to the function when you call it. example, if you want to pass the prop to the action, you can do this in multiple ways.

First:

function mapDispatchToProps(dispatch) {
  return {
    onNameChanged: (name) => dispatch({ type: 'NAME_CHANGED', payload: name })
  }
}

Or

function mapDispatchToProps(dispatch) {
   return {
     actions: bindActionCreator(action, dispatch);
   }
}

from your component just call this.props.actions(propertyFromState). create the action to accept the argument like this in actions.js

function action1(property){
  return { type: 'NAME_CHANGED', payload: property }
}

It is ridiculous that the state cannot be accessed in mapDispatchToProps. There is an alternative to redux, the Dynadux , which is simple and solves Redux's cumbersome.

Useful link: What is mapDispatchToProps?

mapStateToProps() is used to access variables from Redux/application state

function mapStateToProps(state) {
return {
    token: reduxState.token
};
}

It can be accessed inside React Component using this.props.token.

And mapDispatchToProps fires an action event (dispatching an action which may cause change of application state)

const mapDispatchToProps = (dispatch) =>  {
return{
    send:(variable) =>{dispatch(send(variable))}
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM