在redux中API调用成功后调用另一个操作?

问题描述 投票:0回答:1

我正在向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请求来获取更新的对象。

我在代码中的哪个位置?

reactjs api redux
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.