React-Redux计数器示例报错:Actions must be plain objects. 需用自定义中间件处理异步action
解决React-Redux计数器的"Actions must be plain objects"错误
这个错误的核心原因很明确:你调用dispatch(actions.increase())时,actions.increase()返回的不是一个纯JavaScript对象——而Redux默认只接受纯对象类型的action(除非你配置了处理异步action的中间件,比如redux-thunk,但你的计数器是同步场景,完全不需要这个)。
第一步:检查你的Action创建函数
问题大概率出在actions目录下的action创建文件(比如actions/index.js)里。你现在的increase/decrease函数可能写成了类似异步action的格式(返回函数而非对象),或者漏了返回对象。
错误示例(导致报错的写法):
// 错误:返回了函数,不是纯对象 export const increase = () => { return dispatch => { dispatch({ type: INCREASE }); }; }; // 或者错误:没有正确返回对象 export const increase = () => { { type: INCREASE } // 这里缺少return,相当于返回undefined };
正确的同步Action创建函数写法:
修改你的action创建函数,让它们直接返回包含type字段的纯对象:
// actions/index.js import { INCREASE, DECREASE } from './actionTypes'; // 标准写法 export const increase = () => { return { type: INCREASE }; }; export const decrease = () => { return { type: DECREASE }; }; // 更简洁的箭头函数写法(推荐) export const increase = () => ({ type: INCREASE }); export const decrease = () => ({ type: DECREASE });
第二步:优化你的mapDispatchToProps(可选)
你的mapDispatchToProps写法本身没问题,但可以更简洁——connect函数的第二个参数支持直接传入一个包含action创建函数的对象,它会自动帮你绑定dispatch:
import { increase, decrease } from '../actions'; // 替代原来的mapDispatchToProps const mapStateToProps = state => ({ count: state.count }); export default connect(mapStateToProps, { handleIncrease: increase, handleDecrease: decrease })(YourCounterComponent); // 甚至更简单,直接把action函数作为props // export default connect(mapStateToProps, { increase, decrease })(YourCounterComponent); // 然后组件里调用this.props.increase()即可
为什么会出现这个错误?
Redux的核心规则是:action必须是纯对象,用来描述“发生了什么”。如果你的action创建函数返回的是函数(比如异步操作),Redux不知道该怎么处理,这时候才需要引入redux-thunk这类中间件来处理异步逻辑。但你的计数器是完全同步的场景,所以只要保证action是纯对象就可以解决问题。
内容的提问来源于stack exchange,提问作者Armain G. Zamorano
相关产品推荐
相关产品推荐

