javascript - 在 Redux 的 javascript 中包装容器方法的优雅方式

标签 javascript ecmascript-6 redux react-redux

在使用所有相关方法创建一个单独的文件*后,我的 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/

相关文章:

javascript - 动态地将 CSS 应用于单个字符?

javascript - 如何在 ES6 Map 中中断/中断/停止 forEach?

ecmascript-6 - jspm 不会将代码从 ES6 转换为 ES5

reactjs - 使用单独的缩减器 Redux 规范化数据

javascript - 如何通过将 Redux 连接的 React 组件导出为 PureComponent 来测试它?

javascript - jQuery UI 自动完成通过 ajax 错误 :

javascript - 如果B1=空如何通过脚本使A1=空?

javascript - 为什么流行的 JavaScript 运行时不能处理看起来同步的异步脚本?

javascript - 我如何告诉 Redux 不要更新 React 状态?

javascript - Angularjs $compile(html)($scope) - 错误 : Converting circular structure to JSON