繁体   English   中英

使用redux-thunk从动作创建者中访问“ getState”?

[英]Accessing “getState” from within action creator using redux-thunk?

我下面有一个mapDispatchToProps函数。

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

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

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

您的初始语法是错误的,“ hacky”示例也不是您应该怎么做的。

示例如下:

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

而且,不能在mapDispatchToProps内部访问getState本身。 它在thunk中可用,但在mapDispatch不可mapDispatch

您可能想阅读有关为何存在重击的答案 ,以及有关异步操作的Redux文档。

修补错误:/

let ProvidedApp = (serverProps) => {

  let store = getStore(serverProps)

  let ConnectedApp = connect(
    mapStateToProps,
    mapDispatchToProps(store)
  )(App)

  return (
    <Provider store={store}>
      <ConnectedApp/>
    </Provider>
  )
}

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

因此,尽管在您的问题中没有看到您当前的动作创建者,但我将假设它是ES6 / ES2015 JavaScript。

以下内容应使您可以自由地获取任何状态。 既然您有redux-thunk ,那么您应该很好。

export function setActivity(activityName) {
  return function (dispatch, getState) {
    dispatch({
      type: SET_ACTIVITY,
      description: 'Set the name of the activity being done now',
      currentActivityName: activityName,
      currentActivityData: getState().activityStore.activities[activityName]
    });
  };
}

activityStore与您为该特定reducer定义的内容相同,请参见下文。

export const reducers = {
  activityStore: ActivityStore.reducer,
  someOtherStore: SomeOtherStore.reducer
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM