本文介绍了访问“getState"从使用 redux-thunk 的动作创建者内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的 mapDispatchToProps 函数.

I have a mapDispatchToProps function like this one below.

export function mapDispatchToProps(dispatch, ownProps) {
  return {
    handleChangeLang: changeLocaleDispatcher(dispatch),
    handleChange: handleChangeDispatcher(dispatch),
    handleSubmit: handleSubmitDispatcher(dispatch)
  }
}

我刚刚在我的项目中添加了 redux-thunk,这样我就可以从我的动作创建者那里访问 state(认为这是正确的术语).

I just added redux-thunk to my project so I can access state from my action creators (think that's the correct term).

redux-thunk 中似乎没有任何文档概述如何从 mapDispatchToProps 访问 getState.使用 store.dispatch 方法的文档 dispatch.

It doesn't seem there's any documentation in redux-thunk outlining how to access getState from mapDispatchToProps. The docs dispatch using the store.dispatch method.

推荐答案

您的初始语法是错误的,hacky"示例也不是您应该采取的方式.

Your initial syntax is wrong, and the "hacky" example is also not how you should go about it.

示例如下:

import {thunkAction1, thunkAction2} from "myActions";
import {bindActionCreators} from "redux";

const mapDispatchToProps(dispatch) => {
    return {
        manuallyBoundAction : (...args) => dispatch(thunkAction1(...args)),
        autoBoundAction : bindActionCreators(thunkAction2, dispatch),
        multipleActionsTogether : bindActionCreators({thunkAction1, thunkAction2}, dispatch)
    }
};

不,getState 本身在 mapDispatchToProps 中是不可访问的.它在 thunk 中可用,但在 mapDispatch 中不可用.

And no, getState itself is not accessible inside mapDispatchToProps. It's available inside the thunk, but not mapDispatch.

您可能想阅读这个答案关于 thunk 存在的原因,以及关于 异步操作 的 Redux 文档一>.

You may want to read this answer on why thunks exist, as well as the Redux docs on async actions.

这篇关于访问“getState"从使用 redux-thunk 的动作创建者内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 23:46