在Redux中API调用成功后,再调用其他操作吗?

时间:2018-09-10 10:55:55

标签: reactjs api redux

我正在向API端点发出POST请求,该请求应该将属性的布尔值更改为“ true”。

大致而言:

export const toggleToTrue = payload => {
    return (dispatch, getState) => {
        let store = getState();         
        dispatch({ type: "TOGGLE_TO_TRUE", payload });
        return axios
            .post(
                someendpoint,
                { payload },
                {
                    headers: {
                        Authorization: "Bearer " + accessToken,
                        "Content-type": "application/json"
                    }
                }
            )
            .then(res =>
                dispatch({
                    type: "TOGGLE_TO_TRUE_RESOLVE",
                    res: res.data
                })
            )
            .catch(err =>
                dispatch({
                    type: "TOGGLE_TO_TRUE_ERROR",
                    err: err
                })
            );
    };
};

然后在我的减速器上:

case "TOGGLE_TO_TRUE":
    newState.status = action.type;
    newState.error = null;
    return [...state, newState];
    break;
case "TOGGLE_TO_TRUE_RESOLVE":
    if (action.res.errorCode == 0) {
        newState.status = "TOGGLE_TO_TRUE_SUCCESS";
        // Need to dispatch again the action to get updated list
    } else {
        newState.status = "TOGGLE_TO_TRUE_ERROR";
        newState.error = getErrorMessage(action.res);
    }
    return [...state, newState];
    break;
case "TOGGLE_TO_TRUE_ERROR":
    newState.status = action.type;
    newState.error = getErrorMessage(action.err);
    return [...state, newState];
    break;

但是,当前,我的POST请求成功了,因为我没有从该发布请求中获取数据,所以我需要执行另一个GET请求来获取更新的对象。

我在代码中的哪里做?

1 个答案:

答案 0 :(得分:1)

在分派TOGGLE_TO_TRUE_RESOLVE操作后立即:

...
.then(res =>
  dispatch({
    type: "TOGGLE_TO_TRUE_RESOLVE",
    res: res.data
  })
)
.then(callTheApiAgain)
.then(res =>
  dispatch({
    type: "TOGGLE_TO_TRUE_SUCCESS",
    res: res.data
  })
);

但是您还需要在减速器中处理新动作TOGGLE_TO_TRUE_SUCCESS