我正在尝试在react原生中构建一个应用程序,该应用程序假定接受用户的两个输入,然后对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";发布于 2019-07-02 03:47:31
假设您已经添加了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)),
}};https://stackoverflow.com/questions/56840587
复制相似问题