【问题标题】:redux-thunk: actions are not dispatchingredux-thunk:动作没有调度
【发布时间】:2019-11-12 09:36:42
【问题描述】:

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

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

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 函数时该函数将执行,但返回的异步调度具有未定义的行为。

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

start Fetching
JSON file information/Error

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

start Fetching

这是调用fetchData的函数

_onPress = () => {
    let url = "https://randomuser.me/api/?results=10";
    fetchData(url);
    console.log("should have fetched");
  };

这是我添加的mapDispatchToProps 函数。问题是我不知道在函数中添加什么。

const mapStatetoDispatch = (url, dispatch) => {
  return {dispatch(fetchData(url))}; // do not know what to place in body of function

};

我已经用

在组件中连接了它
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

如果需要,这些是我导入的动作创建者

import {
  fetchingSuccess,
  fetchingRequest,
  fetchingFailure,
  fetchData
} from "../data/redux/actions/appActions.js";

【问题讨论】:

  • 尝试 fetchData(url)();但是你必须将它与 react-redux 连接起来,因为 fetchData 不知道 dispatch 是什么。
  • 你的意思是使用mapDispatchToProps 函数吗?如果是这样,你可以为它做出答案。
  • 你有这个回购吗?
  • 我正在为其他人构建这个应用程序,并且我不允许共享存储库。我已经编辑了帖子以反映问题所在。我现在只是对在mapDispatchToProps 函数中放置什么以使dispatch 起作用感到困惑。

标签: react-native redux redux-thunk


【解决方案1】:

假设你已经添加了 redux-thunk 作为中间件,看起来错误就在这里:

_onPress = () => {
  const { fetchData } = this.props;
    let url = "https://randomuser.me/api/?results=10";
    fetchData(url);
    console.log("should have fetched");
  };

const mapStatetoDispatch = dispatch => ({
  fetchData: url => dispatch(fetchData(url)),
}};

【讨论】:

  • 谢谢,这是问题所在,而不是函数本身。
猜你喜欢
  • 2017-08-28
  • 2018-05-21
  • 1970-01-01
  • 2020-03-06
  • 2017-05-25
  • 2020-08-18
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多