Zhicheng Zhang
Zhicheng Zhang

Reputation: 69

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.

Upvotes: 5

Views: 2736

Answers (3)

Dennis T
Dennis T

Reputation: 129

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.

Upvotes: 0

bhuv
bhuv

Reputation: 11

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))}
}
}

Upvotes: -1

Vinod Kolla
Vinod Kolla

Reputation: 324

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 }
}

Upvotes: 3

Related Questions