如何使用redux-thunk实现`bindActionCreators`

时间:2017-11-18 02:06:02

标签: react-native react-redux redux-thunk redux-saga

我对JavaScript很反应并且本机做出反应,我有一个我需要添加功能的现有项目。它使用reduxredux-thunkredux-saga一起发送API请求。目前它每个组件仅支持1 dispatch个函数,我需要dispatch对saga的几种类型的请求。我正在尝试bindActionCreatorsdispatch添加到商店但无济于事。我完全迷失在mapDispatchToProps部分,我如何"触发行动&#34 34;事后..

在发送道具时,我这样做了:

let sdtp = (arg) => {
   return (dispatch) => {
     dispatch({
       type: 'GET_TEST_HASHMAP_SAGA',
       hashmap: arg
     })
   }
 }

export default MainPage = connect(
   mapStateToProps,
   { sdtp }
)(MainPage);

我可以"访问功能" (这是正确的术语吗?至少我的传奇被调用)在MainPage.render()组件中:

`this.props.sdtp({'hello':'world'});`

但是当我改为使用bindActionCreators时,我再也无法在道具中访问它了(我已经尝试了很多不同的实验,我几乎放弃了)

以下是我构建多个调度的方法:

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);

我正试图像这样访问actions

this.props.mdtp.action1({arg: 'hello'});

提前致谢!

3 个答案:

答案 0 :(得分:7)

connect有四个参数......大多数人通常只需要前两个。

mapStateToProps你有,并且我认为它是一个功能。

mapDispatchToProps是第二个......问题出在那里。

bindActionCreators is nothing but a for loop ...不要理会,你会更好地了解正在发生的事情。

试试这个:

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

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

并称他们为 this.props.action1(args)this.props.action2(args)

如果您坚持使用被高估的bindActionCreators语法将是:

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

此外,使用const代替let,因为您没有重新定义该值。最好以与组件的类名不同的名称导出连接的组件。

答案 1 :(得分:2)

在你的mpdt函数中,你需要返回bindActionCreators调用的结果,而不是带有操作键的对象。

所以,它应该是

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

您可以将其称为this.props.action1(...)

从您的代码看来,您似乎还混淆了将动作创建者传递给组件的两种方法。一种方式如上所述。另一方面,您可以使用对象表示法将您的操作创建者直接传递给connect(),如此

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

会有相同的结果。使用sdtp动作创建者的第一种方法是使用此方法。

答案 2 :(得分:1)

或者,您也可以完全跳过mapDispatchToProps ..

render()函数中,您可以直接调用dispatch

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

然后在connect函数中,您可以完全跳过mapDispatchToProps param。

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

我知道这不是答案,但这只是一个可行的替代方案