React-Redux银行表单提交后无法console.log用户详情问题
我帮你排查了代码里的几个关键问题,这些问题导致你点击提交按钮时无法正确打印Redux Store里的用户信息,下面逐一说明并给出修复方案:
1. 提交按钮的事件绑定错误
React的事件属性是驼峰式命名的,你写的onclick应该改为onClick;另外,直接写onClick={this.showUser()}会在组件渲染时就立即执行showUser方法,而不是点击按钮时触发,应该传递函数引用而非执行函数。
修复后的按钮代码:
<button type="button" className="btn btn-success" onClick={this.showUser}>Submit</button>
2. showUser方法未绑定this
在类组件中,自定义方法的this默认不会指向组件实例,所以你需要在constructor中绑定this,否则showUser里的this.props会是undefined。
在constructor中添加绑定:
constructor(props) { super(props) // 保留已有的其他方法绑定 this.setFirstName = this.setFirstName.bind(this); this.setLastName = this.setLastName.bind(this); this.setEmailId = this.setEmailId.bind(this); this.setIban = this.setIban.bind(this); this.setBankName = this.setBankName.bind(this); // 新增showUser方法的this绑定 this.showUser = this.showUser.bind(this); }
3. Reducer中银行账户字段的更新逻辑错误
在处理SET_IBAN和SET_BANKNAME的case时,你没有正确更新user.bankaccounts对象,而是直接在user下添加了iban和bankname属性,导致mapStateToProps中store.user.bankaccounts.iban无法获取到正确的值。
修复后的Reducer对应case:
case 'SET_IBAN':{ return { ...state, user:{ ...state.user, bankaccounts: { ...state.user.bankaccounts, iban: action.payload } } } } case 'SET_BANKNAME':{ return { ...state, user:{ ...state.user, bankaccounts: { ...state.user.bankaccounts, bankname: action.payload } } } }
另外别忘了添加default case,否则Reducer会在匹配不到action时返回undefined:
default: return state;
4. Actions中payload的拼写不一致
你在Actions里返回的是payLoad(大写P),但Reducer里使用的是action.payload(小写p),这会导致Reducer无法正确获取到传入的数值,需要统一拼写为payload(全小写)。
修复后的Actions示例(以setFirstName为例,其他方法同理):
export function setFirstName(firstname){ return { type:SET_FIRSTNAME, payload:firstname } }
修复后验证
完成以上修改后,点击提交按钮就能正确打印出Store里存储的用户信息了。你也可以通过Store的subscribe回调确认数据是否正确更新,确保所有字段的数据流是通畅的。
内容的提问来源于stack exchange,提问作者stone rock

