在 mapDispatchToProps 中绑定动作参数
Bind action parameters in mapDispatchToProps
我有一个将发送操作的提交按钮。该操作的有效负载是将发送到 API 的 post 数据。目前我在 mapDispatchToProps
:
中使用 bindActionCreators
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(FormActions, dispatch)
});
然后在我的组件中,我将 onClick
绑定到提交操作:
<input type="submit" onClick={() => this.props.actions.submit(this.props.postData)} />
我不喜欢我必须在 mapStateToProps
中为该组件提供 post 数据。我宁愿只给组件一个动作,该动作已经将 post 数据绑定到提交函数,因此它的用法如下所示:
<input type="submit" onClick={this.props.submit} />
这可能吗?我无权访问 mapDispatchToProps
中的状态
在 react-redux
的 connect
方法中还有一个名为 mergeProps 的第三个参数,它应该用于您刚才描述的情况。在您的情况下,您可以执行以下操作:
const mapStateToProps = state => ({ postData: ... });
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(FormActions, dispatch)
});
const mergeProps = (stateProps, dispatchProps) => ({
submit: () => dispatchProps.actions.submit(stateProps.postData),
});
const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps)(Component);
请注意,Component 不会收到 actions
或 postData
,只会收到 submit
。
我有一个将发送操作的提交按钮。该操作的有效负载是将发送到 API 的 post 数据。目前我在 mapDispatchToProps
:
bindActionCreators
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(FormActions, dispatch)
});
然后在我的组件中,我将 onClick
绑定到提交操作:
<input type="submit" onClick={() => this.props.actions.submit(this.props.postData)} />
我不喜欢我必须在 mapStateToProps
中为该组件提供 post 数据。我宁愿只给组件一个动作,该动作已经将 post 数据绑定到提交函数,因此它的用法如下所示:
<input type="submit" onClick={this.props.submit} />
这可能吗?我无权访问 mapDispatchToProps
在 react-redux
的 connect
方法中还有一个名为 mergeProps 的第三个参数,它应该用于您刚才描述的情况。在您的情况下,您可以执行以下操作:
const mapStateToProps = state => ({ postData: ... });
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(FormActions, dispatch)
});
const mergeProps = (stateProps, dispatchProps) => ({
submit: () => dispatchProps.actions.submit(stateProps.postData),
});
const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps)(Component);
请注意,Component 不会收到 actions
或 postData
,只会收到 submit
。