【问题标题】:Call another action after API call is successful in redux?在redux中API调用成功后调用另一个动作?
【发布时间】:2019-02-14 19:11:12
【问题描述】:

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

大致如下:

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 请求是成功的,但是由于我没有从这个 post 请求中获取数据,我需要执行另一个 GET 请求来获取更新的对象。

在我的代码中哪里做?

【问题讨论】:

    标签: reactjs api redux


    【解决方案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
      })
    );
    

    但您还需要在 reducer 中处理新操作 TOGGLE_TO_TRUE_SUCCESS

    【讨论】:

    • 就像我需要做的那样 .then(getAPI())..?在上面的示例中,getAPI 是一个类似于 toggleToTrue 的动作创建者?
    • 是的,就像上面一样。
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多