未捕获的类型错误:无法读取未定义的属性(读取“forEach”)..我无法修复它
2022-09-10
729
反复显示此问题...
const reducer = (state, action) => {
switch (action.type) {
case "questions":
action.value.forEach(question => {
question.options.forEach(option => {
option.checked = false
})
})
return action.value
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
2个回答
尝试一下
const reducer = (state, action) => {
switch (action.type) {
case "questions":
(action.value || []).forEach(question => {
(question.options || []).forEach(option => {
option.checked = false
})
})
return action.value
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
Jagan
2022-09-10
首先,您必须检查 action.value 中的值是否存在
const reducer = (state, action) => {
switch (action.type) {
case "questions":
if(action && action.value && action.value.length){
action.value.forEach(question => {
question.options.forEach(option => {
option.checked = false
})
})
return action.value
}
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
如果您使用 forEach,则数组应该有长度。
if(action && action.value && action.value.length){
action.value.forEach(question => console.log(question))
}
Pradeep Kumar
2022-09-10