【问题标题】:Redux-Thunk: async dispatch is not workingRedux-Thunk:异步调度不起作用
【发布时间】:2019-11-12 04:48:58
【问题描述】:

我正在尝试在本机反应中构建一个应用程序,该应用程序假设接受用户的两个输入,然后对 api 进行查询并获取有关这两个输入的信息。我一直在使用 reduxredux-thunk,特别是 async 操作时遇到问题。

这是我的应用程序中我特别遇到问题的代码

export const fetchData = url => {
  console.log("start Fetching");
  return async dispatch => { // this is where the problem is
    dispatch(fetchingRequest());
    try {
      const response = await fetch("https://randomuser.me/api/?results=10");
      const json = await response.text();
      if (response.ok) {
        dispatch(fetchingSuccess(json));
        console.log("JSON", json);
      } else {
        console.log("fetch did not resolve");
      }
    } catch (error) {
      dispatch(fetchingFailure(error));
    }
  };
  console.log("Fetched data");
};

在调试该函数时,我发现当调用fetchData 函数时,该函数将执行,但返回的async dispatch 具有undefined 行为。

调用函数时调试器中的输出应该是

start Fetching
JSON file information/Error

但调试器中的输出实际上是

start Fetching

【问题讨论】:

  • 这个错误解决了吗?

标签: javascript react-native redux redux-thunk


【解决方案1】:

为什么不简单地使用 Promise 语法?

  fetch("https://randomuser.me/api/?results=10")
    .then(response => {
      if (response.ok) {
        // do something
      }
    })
    .catch(e => console.log('fetch did not resolve'));

【讨论】:

  • 我对try and catch块的语法没有问题,所以它成了一种习惯。
猜你喜欢
  • 2017-05-25
  • 2020-01-17
  • 2018-05-30
  • 2023-03-23
  • 2021-01-22
  • 2021-12-11
  • 1970-01-01
  • 2017-10-23
  • 2018-01-31
相关资源
最近更新 更多