【发布时间】:2019-07-02 14:44:30
【问题描述】:
我一直在尝试使用 redux 和 redux-thunk 来帮助从 api 获取 json 文件,并且收到了一条警告,指出 action must be a plain object。我真的很困惑代码中的问题所在。我已经尝试关注许多其他 stackoverflow 帖子和一些在线指南,但并没有真正了解我哪里出错了。我知道这是我引用 async 和 dispatch 的问题,但不知道如何解决。
这是导致警告出现在模拟器中的函数
export const fetchData = url => {
console.log("Should enter async dispatch");
return async (dispatch) => {
dispatch(fetchingRequest());
fetch("https://randomuser.me/api/?results=10")
.then(response => {
if (response.ok) {
let json = response.json();
dispatch(fetchingSuccess(json));
console.log("JSON", json);
}
})
.catch(error => {
dispatch(fetchingFailure(error));
console.log("Error", error);
});
};
};
这是控制台的输出
Possible Unhandled Promise Rejection (id: 0):
Error: Actions must be plain objects. Use custom middleware for async actions.
Error: Actions must be plain objects. Use custom middleware for async actions.
编辑:包括中间件的设置
我的应用程序的 index.js 文件中有中间件设置
index.js
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { Provider } from "react-redux";
import React, { Components } from "react";
import { createStore, applyMiddleware } from "redux";
import appReducer from "./src/data/redux/reducers/appReducer";
import thunk from "redux-thunk";
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(appReducer);
console.log("Store", store.getState());
const AppContainer = () => (
<Provider store = {store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => AppContainer);
我从 Youtube 教程中学习了 store 的这种实现。
编辑2:添加fetchData调用
我在这样的_onPress 函数中调用fetchData
_onPress = () => {
const {fetchData} = this.props;
let url = "https://randomuser.me/api/?results=10";
fetchData(url);
console.log("should have fetched");
};
这就是我的应用连接到redux的方式
const mapStateToProps = state => {
return { response: state };
};
const mapStateToDispatch = dispatch => ({
fetchData: url => dispatch(fetchData(url)),
});
export default connect(
mapStateToProps,
mapStateToDispatch
)(SearchScreen);
这些是我的应用程序中的操作
export const fetchingRequest = () => {
{
type: FETCHING_REQUEST;
}
};
export const fetchingSuccess = json => {
{
type: FETCHING_SUCCESS;
payload: json;
}
};
export const fetchingFailure = error => {
{
type: FETCHING_FAILURE;
payload: error;
}
};
【问题讨论】:
-
首先要消除的是设置。请包含您如何创建商店的代码,以确保您正确应用了 thunk 中间件。
-
抱歉,我已经添加了商店的设置。
-
OK 看起来不错,但您可能对 this 作为创建商店的清洁/推荐模式感兴趣。接下来是你怎么打电话给
fetchData?请在您的问题中也包含该代码。这些请求可能看起来很乏味,但它们都是 How to Ask a Good Question 的一部分,并且是 MCVE - 它使这个问题对未来的用户很有价值。 -
我已经包含了我是如何被称为
fetchData以及我如何将它连接到redux以防万一需要它。 -
复制粘贴您的代码,我没有收到任何错误。但是,我已经用普通对象替换了
fetchingRequest、fetchingSuccess和fetchingFailure,因为我假设这些函数会返回这些对象。接下来是一个明显的问题:你安装了 redux-thunk 库吗?
标签: react-native redux redux-thunk