how to `bindActionCreators` with redux-thunk
我对JavaScript和react-native还是很陌生,并且已经有需要添加功能的现有项目。 它使用
在一次派发道具时,我这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 | let sdtp = (arg) => { return (dispatch) => { dispatch({ type: 'GET_TEST_HASHMAP_SAGA', hashmap: arg }) } } export default MainPage = connect( mapStateToProps, { sdtp } )(MainPage); |
并且我可以在
1 | `this.props.sdtp({'hello':'world'});` |
但是当我更改为使用
这是我构造多个调度的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | let action1 = (args) => { return (dispatch) => { dispatch({ type: 'GET_TEST_HASHMAP_SAGA', hashmap: arg }); } } let action2 = (args) => { return (dispatch) => { dispatch({ type: 'GET_TEST_HASHMAP_SAGA2', params: arg }); } } let action3 = (args) => { return (dispatch) => { dispatch({ type: 'GET_TEST_HASHMAP_SAGA3', args: arg }); } } let mdtp = (dispatch) => { return { actions: bindActionCreators(action1, action2, action3, dispatch) } } export default MainPage = connect( mapStateToProps, { mdtp } )(MainPage); |
我正在尝试像这样访问
提前致谢!
尝试这个:
1 2 3 4 5 6 7 8 9 10 11 | function mapDispatchToProps(dispatch) { return { action1: (args) => dispatch(action1(args)), action2: (args) => dispatch(action2(args)), } } export default MainPageContainer = connect( mapStateToProps, mapDispatchToProps )(MainPage) |
并称他们为
如果您坚持使用高估的
1 2 3 4 5 6 7 8 | function mapDispatchToProps(dispatch){ return { actions: bindActionCreators({ action1, action2, }, dispatch) } } |
另外,因为您没有重新定义值,所以使用
在mpdt函数中,您需要返回
所以应该
1 2 3 4 5 | const mdtp = (dispatch) => { return bindActionCreators({ action1, action2, action3 }, dispatch); }; |
您可以将它们称为
从代码中还可以看出,您已经混淆了将操作创建者传递给组件的两种方法。上面描述了一种方式。另外,您可以使用对象符号将动作创建者直接传递给
1 2 3 4 | export default MainPage = connect( mapStateToProps, { action1, action2, action3 } )(MainPage); |
会有相同的结果。而您的第一种方法,与
或者,您也可以完全跳过
在您的
然后在
1 2 3 | export default MainPage = connect( mapStateToProps )(MainPage); |
我知道这不是答案,但这只是一个可行的替代方案