React-Redux异步请求报错:Actions必须是纯对象,需用自定义中间件
解决Redux中"Actions must be plain objects"异步Action错误
嘿,这个错误我太熟了!问题出在Redux的默认规则上:它只认普通JavaScript对象作为action,但你写的getNewsAPI返回的是一个函数(就是那个(dispatch, getState) => {...}),这就超出了Redux默认的处理范围了。要支持这种异步action,你得给Redux加个中间件——最常用的就是redux-thunk。
下面一步步来解决:
1. 先安装redux-thunk
打开终端,运行:
npm install redux-thunk # 或者用yarn的话 yarn add redux-thunk
2. 给Redux Store配置thunk中间件
找到你创建Redux store的文件(通常是store.js或者redux/store.js),修改成这样:
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './path-to-your-root-reducer'; // 换成你自己的根reducer路径 // 把thunk加入中间件列表 const store = createStore( rootReducer, applyMiddleware(thunk) ); export default store;
3. 调整你的Action(写法本身没问题,配合中间件即可)
另外注意你action里用了字符串'API_REQUEST',但你已经导入了types模块,建议用常量代替字符串,避免拼写错误。我给你补全了完整的异步请求逻辑:
import * as types from './newsApiTypes'; const API_KEY = "6c78608600354f199f3f13ddb0d1e71a"; export const getNewsAPI = () => { return (dispatch, getState) => { // 先分发一个请求开始的action,用来显示loading状态之类的 dispatch({ type: types.API_REQUEST, options: { method: 'GET', endpoint: `https://newsapi.org/v2/top-headlines?country=us&apiKey=${API_KEY}` // 补全你的请求参数,比如country、category等 } }); // 发起实际的API请求,成功和失败时分发对应的action fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=${API_KEY}`) .then(response => response.json()) .then(data => { dispatch({ type: types.NEWS_FETCH_SUCCESS, payload: data }); }) .catch(error => { dispatch({ type: types.NEWS_FETCH_FAILURE, payload: error.message }); }); } };
为啥这样就能解决?
redux-thunk的作用就是让Redux允许action返回函数,这个函数可以拿到dispatch和getState方法,让你能在异步操作(比如API请求)完成后,再分发普通对象类型的action,完全符合Redux的要求。
最后别忘了,你的reducer里要对应处理这些action类型(API_REQUEST、NEWS_FETCH_SUCCESS、NEWS_FETCH_FAILURE),这样才能正确更新state并渲染到页面上哦~
内容的提问来源于stack exchange,提问作者Eunicorn
相关产品推荐
相关产品推荐

