how to `bindActionCreators` with redux-thunk

微笑、不失礼 提交于 2019-12-05 08:44:32
parker

connect takes four arguments...most people usually only need the first two.

mapStateToProps you have, and I'm assuming it's a function.

mapDispatchToProps is the second...the issue is there.

bindActionCreators is nothing but a for loop...leave it out and you will better understand what is happening.

Try this:

function mapDispatchToProps(dispatch) {
  return {
     action1: (args) => dispatch(action1(args)),
     action2: (args) => dispatch(action2(args)),
  }
}

 export default MainPageContainer = connect(
   mapStateToProps,
   mapDispatchToProps
 )(MainPage)

And call them as this.props.action1(args) and this.props.action2(args)

If you insist on using the overrated bindActionCreators the syntax would be:

 function mapDispatchToProps(dispatch){
   return {
     actions: bindActionCreators({
       action1,     
       action2,
     }, dispatch)
   }
 }

Also, use const instead of let since you are not redefining the value. It is also best to export the connected component under a different name than the class name of the component.

In your mpdt function, you need to return result of bindActionCreators call, not object with action key.

So, it should be

const mdtp = (dispatch) => {
  return bindActionCreators({
    action1, action2, action3
  }, dispatch);
};

and you can call them as this.props.action1(...)

From your code it also seems, that you have confused two ways of passing action creators to the component. One way is described above. And another way, you can pass your action creators directly to connect() using object notations, like so

export default MainPage = connect(
   mapStateToProps,
   { action1, action2, action3 }
)(MainPage);

which will have same result. And your first approach, with sdtp action creator uses this approach.

Alternatively, you can also skip mapDispatchToProps entirely..

Within your render() function, you can just call dispatch directly like this:

this.props.dispatch({type: 'GET_TEST_HASHMAP_SAGA2', params: {"hello": "world"}});

Then in your connect function, you can skip the mapDispatchToProps param entirely.

export default MainPage = connect(
   mapStateToProps
)(MainPage);

I know this isn't the answer, but this is just an alternative that works as well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!