【问题标题】:How to return the result of " axios' POST request " from reducer function in react如何在react中从reducer函数返回“axios'POST请求”的结果
【发布时间】:2022-01-04 07:32:34
【问题描述】:

我正在从 dispatch 函数发送数据(字符串)并且想要返回作为 POST 请求的结果返回的对象,但是由于 axios 是异步工作的,return 语句在 POST 请求的结果之前执行。请帮忙

dispatch({ type: "INCREASE_VOTES_QUESTION", payload: loginUser.id })

export default function reducer(state, action) {

    if (action.type === "INCREASE_VOTES_QUESTION") {
        let updatedSingleQuestion
        axios({
            method: "POST",
            url: `http://localhost:5000/questions/${question_id}/votes-update`,
            withCredentials: true,
            data: { action: "increase", id: action.payload },
        }).then((res) => {
            updatedSingleQuestion = res.data
        })
        return updatedSingleQuestion
    }
}

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

reducer 函数不应该自己进行调用。它们应该是没有副作用的纯函数。通过 axios 调用 API 被认为是副作用。

更好的选择是将您的逻辑封装在一个函数中(或提取到一个钩子中),然后使用 axios 调用的结果分派一个动作。

function incrementCount(questionId, dispatch) {
  axios({
    method: "POST",
    url: `http://localhost:5000/questions/${questionId}/votes-update`,
    withCredentials: true,
    data: { action: "increase", id: action.payload },
  }).then((res) => {
    dispatch({type: "QUESTION_VOTES_CHANGED", payload: {questionId, votes: res.data}});
  });
}

现在你的 reducer 函数可以处理 QUESTION_VOTES_CHANGED 动作了:

function reducer(state, action) {
  if (action.type === "QUESTION_VOTES_CHANGED") {
    return {
      ...state,
      [action.payload.questionId]: action.payload.votes
    };
  }

  return state;
}

这将适用于如下所示的状态:

{
  "Question1": 1,
  "Question2": 8
}

【讨论】:

    【解决方案2】:

    不幸的是,reducer 不能向调用它的代码返回任何值。正如this 文档所述:

    Reducers are functions that take the current state and an action as arguments, and return a new state result.

    另一方面,您可以在 reducer 中更新您的商店,并通过为您的客户端代码订阅更新来获取新值。

    Here 很好地说明了整个流程。

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2022-09-24
      • 2018-06-29
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      相关资源
      最近更新 更多