首页 > 解决方案 > 解决 redux reducer 中的承诺?

问题描述

我有一个使用 redux 的 reactjs 项目。我正在发出以下获取请求:

function fetchQuote() {
  return fetch("http://localhost:8080/quote").then(function (response) {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    // Read the response as json.
    return response;
  })
    .then(function (response2) {
      // Do stuff with the JSON
      return response2.text();
    })
    .then(function (response3) {
      return response3
    })
    .catch(function (error) {
      console.log('Looks like there was a problem: \n', error);
    })
}

我想用这个函数在我的项目后端返回一个字符串的值。我通过我的动作创建器访问此功能,如下所示:

export const getQuote = () => ({ type: 'GET_QUOTE', payload: fetchQuote() });

然后进入减速器:

const quoteReducer = (state = { title: 'test', id: 1 }, action) => {
  switch (action.type) {
    case GET_QUOTE:
      console.log(action);
      return [...state, action.payload];
    default:
      return state;
  }
};

但是,当我console.log(action)得到以下信息时:

{type: "GET_QUOTE", payload: Promise}
payload
:
Promise
__proto__
:
Promise
[[PromiseStatus]]
:
"resolved"
[[PromiseValue]]
:
"tes11t"
type
:
"GET_QUOTE"

我希望解决这个承诺,以便我可以直接访问 fetch 请求返回的值。但我不知道该怎么做?

标签: javascriptreactjsreduxreact-redux

解决方案


那是因为getQuote将 Promise 传递给 reducer,而不是返回值。但你知道的。

在这种情况下,您必须异步执行某些操作并调度在异步操作完成返回值的操作。您不能在传递的 Object 中执行此操作,但可以使用 redux 中间件。有一些库旨在解决诸如redux-thunkredux-saga等问题redux-observable


推荐阅读