redux-thunk:操作未调度

时间:2019-07-01 18:20:12

标签: react-native redux redux-thunk

我正在尝试在react native中构建一个应用程序,该应用程序假设用户接受两个输入,然后查询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";

1 个答案:

答案 0 :(得分:2)

假设您已添加redux-thunk作为中间件,则错误似乎在这里:

const EXPRESS = require('express');
const BODY_PARSER = require('body-parser');
const PATH = require('path');

const APP = EXPRESS();

const ADMIN_ROUTES = require('./routes/admin');
const SHOP_ROUTES = require('./routes/shop');

APP.use(BODY_PARSER.urlencoded({ extended: false }));

APP.use('/admin', ADMIN_ROUTES);
APP.use(SHOP_ROUTES);

APP.use((req, res, next) => {
  console.log('page not found');
  res
    .status(404)
    .sendFile(PATH.join(__dirname, '../', 'views', 'not-found.html'));
});

APP.listen(4000);

List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
for(int i=0; i< batchSize; i++) {
stringRedisConn.rPop("myqueue");
}
return null;
}
});