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

不羁的心 提交于 2019-12-12 03:26:38

问题


I have a mapDispatchToProps function like this one below.

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

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

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.


回答1:


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

A sample would look like:

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

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

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




回答2:


So while I don't see your current action creator in your question, I will assume it's ES6/ES2015 javascript.

The below should give you freedom to grab any state. Since you have redux-thunk, you should be good to go.

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 is same as what you've defined for that particular reducer, see below.

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



回答3:


Hacky fix :/

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


来源:https://stackoverflow.com/questions/36461139/accessing-getstate-from-within-action-creator-using-redux-thunk

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