首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >redux-thunk:未调度操作

redux-thunk:未调度操作
EN

Stack Overflow用户
提问于 2019-07-02 02:20:12
回答 1查看 266关注 0票数 0

我正在尝试在react原生中构建一个应用程序,该应用程序假定接受用户的两个输入,然后对api进行查询,并获取关于这两个输入的信息。我在redux和redux-thunk方面遇到了麻烦,特别是异步操作。

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

代码语言:javascript
复制
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函数时,函数将执行,但返回的异步调度具有未定义的行为。

调用函数时,调试器中的输出应为

代码语言:javascript
复制
start Fetching
JSON file information/Error

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

代码语言:javascript
复制
start Fetching

这是在其中调用fetchData的函数

代码语言:javascript
复制
_onPress = () => {
    let url = "https://randomuser.me/api/?results=10";
    fetchData(url);
    console.log("should have fetched");
  };

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

代码语言:javascript
复制
const mapStatetoDispatch = (url, dispatch) => {
  return {dispatch(fetchData(url))}; // do not know what to place in body of function

};

我在组件中将其连接到

代码语言:javascript
复制
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

如果需要,这些是我导入的操作创建器

代码语言:javascript
复制
import {
  fetchingSuccess,
  fetchingRequest,
  fetchingFailure,
  fetchData
} from "../data/redux/actions/appActions.js";
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-02 03:47:31

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

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

代码语言:javascript
复制
const mapStatetoDispatch = dispatch => ({
  fetchData: url => dispatch(fetchData(url)),
}};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56840587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档