使用Redux存储员工数据时mapStateToProps调用两次且返回空数组问题
问题分析与解决方案
看起来你遇到了两个核心问题:mapStateToProps被调用两次且第二次返回空数组,以及员工数据没有正确添加到Redux Store中。我们一步步来解决:
1. 页面刷新导致Store重置(第二次调用返回空数组的根源)
你的表单提交时没有阻止浏览器的默认行为!当点击Submit按钮时,浏览器会触发form的默认提交动作,导致页面刷新,Redux Store会被重置为初始状态(employeeDetails: []),所以第二次调用mapStateToProps时拿到的就是空数组。
修复方法:修改handleFormSubmit方法,添加事件参数并阻止默认行为:
handleFormSubmit = (evt) => { evt.preventDefault(); // 阻止表单默认提交,避免页面刷新 debugger; let employDet = { empName: this.state.empName, empId: this.state.empId, emailId: this.state.emailId, empAge: this.state.empAge } this.props.dispatch(addEmployee(employDet)) }
另外,建议给提交按钮明确设置原生type="button"(如果你的Button组件支持传递该属性),彻底避免默认submit行为:
<Button action={this.handleFormSubmit} type={"primary"} htmlType="button" // 传递原生button的type属性 title={"Submit"} className="buttonStyle" />
2. Reducer中员工数据添加逻辑错误
你的Reducer尝试用action.index来插入数据,但addEmployee Action并没有传递index参数,导致action.index是undefined,这会让数组拼接逻辑完全不符合预期(会把原数组重复一遍再加新数据)。
如果你只是想追加新员工到数组末尾
直接修改Reducer的ADD_EMPLOYEE分支:
case AppConstants.ADD_EMPLOYEE: // 直接在原数组末尾添加新数据,简洁且符合预期 return {...state, employeeDetails: [...state.employeeDetails, action.payload] }
如果你需要插入到指定位置
先修改Action,让它接收index参数:
// action/index.js export const addEmployee = (empData, index) => { return dispatch => { dispatch({ type: AppConstants.ADD_EMPLOYEE, payload: empData, index }) }; }
然后在提交表单时传递目标index(比如数组长度,即追加到末尾):
// 在EmployeeForm的handleFormSubmit中 this.props.dispatch(addEmployee(employDet, this.props.employeeDetails.length))
这样原Reducer的插入逻辑就能正常工作了。
3. 额外优化建议
- 简化
mapStateToProps的写法:const mapStateToProps = state => ({ employeeDetails: state.employeeDetails }); - 提交表单后清空输入框,提升用户体验:
handleFormSubmit = (evt) => { evt.preventDefault(); let employDet = { empName: this.state.empName, empId: this.state.empId, emailId: this.state.emailId, empAge: this.state.empAge } this.props.dispatch(addEmployee(employDet)) // 清空表单输入 this.setState({ empName: "", empId: "", emailId: "", empAge: "" }) }
按照这些步骤修改后,你的Redux Store就能正确存储员工数据,mapStateToProps也不会再返回空数组了。
内容的提问来源于stack exchange,提问作者Praveena Padvetnaya
相关产品推荐
相关产品推荐

