在使用所有相关方法创建一个单独的文件*后,我的 mapDispatchToProps 方法是:
const mapDispatchToProps = (dispatch, ownProps) => {
return {
toggleTreeMode: () => {dispatch(editor_thunks.toggleTreeMode());},
toggleDrawer: (e) => {dispatch(editor_thunks.toggleDrawer(e));},
toggleDataButtons: (on) => {dispatch(editor_thunks.toggleDataButtons(on));},
//... many more methods
}
签名都是一样的,所以感觉 ES6 中一定有更好的方法来包装它。有吗?
这行不通,因为我需要派送:
const mapDispatchToProps = (dispatch, ownProps) => {
return editor_thunks;
}
*大多数方法都需要状态,所以感觉这是最好的解决方案
最佳答案
您可以使用 mapDispatchToProps()
速记符号。参数 mapDispatchToProps
可以是配置对象,而不是函数。根据react-redux docs :
[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.
这意味着如果你只需要用dispatch包装所有的action,你可以传递一个方法对象,对象中的每个方法都会自动包装在dispatch
中。
如果您需要 editor_thunks 的一些操作
const { toggleTreeMode, toggleDrawer, toggleDataButtons } = editor_thunks;
connect(mapStateToProps, { toggleTreeMode, toggleDrawer, toggleDataButtons })(Component);
如果您需要 editor_thunks 的所有操作
connect(mapStateToProps, editor_thunks)(Component);
关于javascript - 在 Redux 的 javascript 中包装容器方法的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180666/