多次呼叫后无法获取更新状态

时间:2019-06-19 13:38:16

标签: reactjs redux react-redux dispatch

我正在使用带有React的redux来管理状态,但是当我从一个动作创建者调用了两个调度函数时,它是从第一次调度返回的状态,但是在另一个调度调用之后无法获取更新的状态。

我尝试从不同的reducer调用调度,并尝试在API调用之后调用。

这是我的动作。

export const setLoader = (loader) => dispatch => {
  dispatch({ type: SET_LOADER, payload: loader });
};

export const fetchCategory = (setLoader) => async dispatch => {
    setLoader(true);
    try {
        const instance = axios.create();
        instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
        const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);

        dispatch({ type: FETCH_CATEGORY, payload: response.data });

    } catch (e) {
      setLoader(false);
    }

};

我在这里定义了减速器:

export default (state = INITIAL_STATE, action) => {

    switch (action.type) {
    case FETCH_CATEGORY:
        return { ...state, categoryList: action.payload };
    case SET_LOADER:
        return { ...state, isLoading: action.payload };
    default:
        return state;
    }
};

在这里,我的组件与redux连接:

const mapStateToProps = state => {
  return ({
      categoryList: state.locator.categoryList
  });
}

export default connect(
    mapStateToProps,
    { fetchCategory, setLoader }
)(ServiceLocator);

我希望输出返回更新的categoryList,但实际上它返回一个空白数组。

1 个答案:

答案 0 :(得分:0)

您正在动作创建器中执行异步任务,如果没有中间件,Redux将无法处理该任务。我建议使用中间件redux-thunk。这样一来,您就可以在操作创建者中执行异步操作,并分派多次。

希望这会有所帮助!


更新:

如果您已安装redux-think中间件并将其添加到Redux(根据您的评论),那么接下来我将看一下setLoader()-似乎该函数已被管理,我不认为您希望如此。我将删除setLoader()步骤,并直接从fetchCategory()调度该动作:

export const fetchCategory = () => async dispatch => {
  dispatch({ type: SET_LOADER, payload: true });
  try {
    const instance = axios.create();
    instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
    const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);

    dispatch({ type: FETCH_CATEGORY, payload: response.data });

  } catch (e) {
    dispatch({ type: SET_LOADER, payload: false });
  }
};
相关问题