如何使用 redux-thunk `bindActionCreators`

how to `bindActionCreators` with redux-thunk

我对 JavaScript 和 react-native 很陌生,我有一个现有项目需要添加功能。它使用 reduxredux-thunk 以及 redux-saga 来发送 API 请求。目前它只支持每个组件 1 dispatch 个函数,我需要 dispatch 对 saga 的几种类型的请求。我正在尝试 bindActionCreatorsdispatch 添加到商店,但无济于事。我完全迷失了 mapDispatchToProps 部分,之后我该如何 "fire the action" ..

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

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

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

我可以在 MainPage.render() 组件中 "access the function"(这是正确的术语吗?至少我的 saga 被调用了):

`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'});

提前致谢!

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,因为您没有重新定义该值。最好以与 class 组件名称不同的名称导出连接的组件。

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

所以,应该是

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

你可以称他们为 this.props.action1(...)

从您的代码看来,您还混淆了将动作创建者传递给组件的两种方式。上面描述了一种方法。另一种方法是,您可以使用对象符号将动作创建者直接传递给 connect(),例如

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

这将有相同的结果。而您的第一种方法,sdtp 动作创建者使用这种方法。

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

在您的 render() 函数中,您可以像这样直接调用 dispatch

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

然后在你的 connect 函数中,你可以完全跳过 mapDispatchToProps 参数。

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

我知道这不是答案,但这只是一个同样有效的替代方案