React登录页includes()报错:无法读取undefined的includes属性
解决React useReducer中includes()调用的"Cannot read properties of undefined"错误
问题根源
你的错误并非时序问题,而是reducer中属性访问的逻辑错误:
- 在处理
INPUT_BLUR类型的action时,你尝试访问action.value(邮箱校验)和action.value(密码校验),但触发onBlur时dispatch的action只传入了type: 'INPUT_BLUR',没有携带value属性,导致action.value为undefined,调用includes()或trim()时就会抛出错误。 - 实际上,当触发
onBlur时,输入框的最新值已经保存在reducer的state中,完全不需要从action里取值。
修复代码
修改两个reducer中的INPUT_BLUR分支逻辑,改用state.value进行校验:
修复后的emailReducer
const emailReducer = (state, action) => { if (action.type === 'USER_INPUT') { console.log(action.val); return { value: action.val, isValid: action.val.includes('@') }; } if (action.type === 'INPUT_BLUR') { // 从state中读取当前值,而非action return { value: state.value, isValid: state.value.includes('@') }; } return { value: '', isValid: false }; };
修复后的passwordReducer
const passwordReducer = (state, action) => { if (action.type === 'USER_INPUT') { return { value: action.val, isValid: action.val.trim().length > 6 }; } if (action.type === 'INPUT_BLUR') { // 从state中读取当前值,而非action return { value: state.value, isValid: state.value.trim().length > 6 }; } return { value: '', isValid: false }; }
补充说明
你之前用console.log(action.val)能看到值,是因为那是在USER_INPUT分支——这个分支的action确实携带了val属性,但INPUT_BLUR的action没有传递任何额外数据,所以访问action.value必然会得到undefined。
内容的提问来源于stack exchange,提问作者Hanson Liao
相关产品推荐
相关产品推荐

