React中如何访问mapStateToProps定义的props数据?
问题解决方法
你的问题核心是函数组件中不存在this对象,不能用类组件的this.props方式获取属性。函数组件的props是直接作为参数传入组件的,修正方式如下:
基础修正方案
给组件函数添加props参数,直接通过参数访问employees:
const mapStateToProps = (state) => { return { users: state.gf.users, employees: state.gf.employees, } } // 给组件传入props参数 const EmployeeListFilter = (props) => { const getEmployees = () => { // 直接使用props.employees替代this.props.employees let employees = props.employees } useEffect(() => { if (empId) { getEmployees() } }, [empId]) } // 确保组件已和Redux store连接 export default connect(mapStateToProps)(EmployeeListFilter)
简洁优化方案(解构赋值)
可以通过解构赋值直接从props中提取employees,让代码更简洁:
const mapStateToProps = (state) => { return { users: state.gf.users, employees: state.gf.employees, } } // 解构props中的employees const EmployeeListFilter = ({ employees }) => { const getEmployees = () => { // 直接使用解构后的变量 let empList = employees } useEffect(() => { if (empId) { getEmployees() } }, [empId]) } export default connect(mapStateToProps)(EmployeeListFilter)
关键说明
函数组件与类组件的props获取逻辑完全不同:
- 类组件依赖
this.props访问属性 - 函数组件的props是组件函数的第一个入参,直接调用即可
你的mapStateToProps逻辑是正常的,只要修正props的访问方式,就能成功获取到Redux store中的员工列表。
内容的提问来源于stack exchange,提问作者J.Cart
相关产品推荐
相关产品推荐

