Assume you have some component and action creator mapped to props via mapDispatchToProps and you need to pass props.id into that action creator. Currently you need to create some handleRemove method, which in turn remove action creator with id from props. But it would be nice if you can call remove action creator without any param and params can be taken from props instead directly.
class CurrentSituationComponent extends Component {
handleRemove() {
this.props.remove(this.props.id);
}
render() {
<div onClick={this.props.handleRemove}/>
}
}
class SuggestedComponent extends Component {
render() {
<div onClick={this.props.remove}/>
}
}
const mapDispatchToProps = (dispatch) => {
return {
remove: () => {
dispatch(removeById(this.props.id));
}
};
};
const mapStateToProps = (state, ownProps) => {
const id = ownProps.params.id;
return { id };
};
export default connect(mapStateToProps, mapDispatchToProps)(SuggestedComponent);
Did you mean to file it in https://github.com/rackt/react-redux instead?
You should already be able to implement this with the optional ownProps argument:
const mapDispatchToProps = (dispatch, ownProps) => {
return {
remove: () => {
dispatch(removeById(ownProps.id));
}
};
};
Note, however, that this will be slower because it will require re-binding the action creators whenever props change.
Ach sorry for wrong repo.
But IMHO ownProps is not solution here as id is coming from state, not passed from parent in form of props.
Wrapping component can鈥檛 possible access wrapped component鈥檚 state so you have to hoist it up to the parent component.
There seems to be two ways to access wrapped component's state in mapDispatchToProps, aside from hoisting it up, you can also use redux-thunk to access getState(). Which do you think is more advisable? @gaearon
Sorry for replying to this wrongly placed issue.
Both are fine IMO.
Got it working by
connect(mapStateToProps, mapEmptyToProps)(connect(mapStateToProps, mapDispatchToProps)(MyComponent))
use mergeProps, read the docs from
here
Most helpful comment
Did you mean to file it in https://github.com/rackt/react-redux instead?
You should already be able to implement this with the optional
ownPropsargument:Note, however, that this will be slower because it will require re-binding the action creators whenever props change.