Redux-Thunk getStore()不保留状态。返回'undefined'

时间:2018-06-07 03:17:30

标签: javascript reactjs redux redux-thunk

这可能是最佳实践的问题,但我很感激为什么这不起作用的解释。我正在使用Typescript + Redux + Thunk并试图调用这样的动作:

export const requestUserDashboards  = createAction<DashboardModel>(Type.REQUEST_USER_DASHBOARDS);

在fetch中发送:

export const fetchDashboards = () => {
        return async (dispatch: Dispatch, getState: any) => {
            try {
                dispatch(requestUserDashboards({ 
                    currentDashboard: getState.currentDashboard,
                    dashboards: getState.dashboards,
                    hasDashboards: false,
                    error: getState.error
                }))

             ...
             }
         })
}

这是相应的减速器:

export const dashboardReducer = handleActions<RootState.DashboardState, DashboardModel>(
  {
    [DashboardActions.Type.REQUEST_USER_DASHBOARDS]: (state = initialState, action): RootState.DashboardState => ({
      currentDashboard: action.payload!.currentDashboard,
      dashboards: action.payload!.dashboards,
      hasDashboards: action.payload!.hasDashboards,
      error: action.payload!.error
    })
  },
  initialState
);

dispatch正在运行,但getState未正确收集当前存储状态。我正在通过在接收更新的商店的组件中执行以下操作来测试它:

componentWillReceiveProps(nextProps: Login.Props) {
    console.log(nextProps.defaultAccounts.defaultAccount);
}

使用以下方法在组件中调用:

this.props.defaultAccountActions.fetchUserDefaultAccount();

当捕获来自获取的值时,操作正在运行。

但是,在我使用getState.xxxx的地方,这些值将返回为undefined:

index.tsx:84 Uncaught TypeError: Cannot read property 'defaultAccount' of undefined

我的reducer的initialState正在运行。我可以通过console.log(this.props.defaultAccounts.defaultAccount)函数执行componentWillMount()来看到这一点。

我不确定我能提供什么。我想我实际上只是从根本上误解了行动/减少者如何管理商店。

问题

我试图通过在调度中使用getState.xxxx来获取当前商店值。这是正确的方法吗?

2 个答案:

答案 0 :(得分:3)

不是getState在那个地方的一个函数吗?所以你需要做点什么

 const state = getState();

然后在调度内使用状态

在文档中找到,是的,它是该地方的一个函数,所以你应该首先调用一个函数来获取状态然后使用它(例如,从下面的文档中)

function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState();

    if (counter % 2 === 0) {
      return;
    }

    dispatch(increment());
  };
}

答案 1 :(得分:1)

如果您在组件中使用mapstatetoprops,则可以使用它来从商店获取值。 mapStateToProps的第一个参数实际上是Redux状态。它实际上是一个抽象的getState()。

const mapStateToProps = function(state, ownProps) {
   // state is equivalent to store.getState()
   // you then get the slice of data you need from the redux store
   // and pass it as props to your component

   return {
     someData: state.someData
   }
}