如何将Redux的dispatch方法作为props传入类组件?
嘿,我来帮你搞定类组件里把Redux的dispatch直接作为props传入的问题!其实核心逻辑和函数组件是一致的,只是类组件需要结合connect高阶组件的特性来实现,下面给你详细说明:
类组件中注入dispatch作为props的方法
本质上,react-redux的connect高阶组件有个实用特性:当你不提供第二个参数(mapDispatchToProps),或者传入null/undefined时,它会自动把Redux store的dispatch方法作为props注入到组件中。
结合你给出的代码片段,我给你修改后的完整可运行示例:
import React, { Component } from 'react'; import { connect } from 'react-redux'; // 你的action creator(注意原代码漏了return,我补上了) function addData(data) { return { type: "ADD_DATA", data }; } class MainComponent extends Component { handleAddData = () => { // 直接通过this.props.dispatch调用action this.props.dispatch(addData({ content: '测试数据' })); }; render() { return ( <button onClick={this.handleAddData}>添加数据到Store</button> ); } } // 关键:connect的第二个参数留空或传null,dispatch就会自动注入 export default connect()(MainComponent); // 也可以写成 export default connect(null)(MainComponent); 效果完全一致
额外补充场景
如果你已经自定义了mapDispatchToProps来绑定action creators,但还是想同时拿到dispatch,可以手动把它加入返回对象:
const mapDispatchToProps = (dispatch) => { return { // 绑定好的action方法 addData: (data) => dispatch(addData(data)), // 手动把dispatch注入props dispatch }; }; export default connect(null, mapDispatchToProps)(MainComponent);
这样不管是直接用dispatch,还是用绑定好的action方法,都能在类组件里正常使用啦!
内容的提问来源于stack exchange,提问作者Max Wolfen
相关产品推荐
相关产品推荐

