React父组件向子组件传递questionAnswerPair时出现undefined问题
问题核心原因
- Props命名不匹配:父组件调用
QuestionAnswer子组件时,传递题目的属性名是parentToChild,但子组件解构参数时接收题目的变量名是currentQuestionAnswerPair,二者名称不一致,子组件自然无法拿到对应值,输出为undefined。 - 循环赋值逻辑错误:你在for循环中多次调用
setCurrentQuestionAnswerPair,React状态更新是批量异步执行的,循环结束后状态只会保留最后一个questionAnswerPair的值,前面的所有赋值都会被覆盖。
修复步骤
- 修正Props命名,将父组件的子组件调用代码修改为:
<QuestionAnswer currentQuestionAnswerPair={currentQuestionAnswerPair} childToParent={childToParent} />
- 修正子组件useEffect依赖,确保props变化时同步更新本地状态:
useEffect(() => { console.log(currentQuestionAnswerPair) setQuestionAnswer(currentQuestionAnswerPair) }, [currentQuestionAnswerPair]) // 新增依赖项
- 优化逐题遍历逻辑(可选,解决当前只能显示最后一题的问题):
新增当前题号的状态控制,代替直接在循环里批量赋值:
// 父组件新增状态 const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0) // 拉取到quiz数据后加载第一题 useEffect(() => { if (executedFetch === true && quiz.questionAnswerPairs?.length) { setCurrentQuestionAnswerPair(quiz.questionAnswerPairs[currentQuestionIndex]) setExecutedIterate(true) } }, [executedFetch, currentQuestionIndex, quiz]) // 用户答完题后调用此方法切换下一题 const goNextQuestion = () => { if (currentQuestionIndex < quiz.questionAnswerPairs.length - 1) { setCurrentQuestionIndex(prev => prev + 1) } }
另外建议优化状态初始化类型,你当前存储对象/数组的状态初始值设为了空字符串,建议改为useState(null)或者对应类型的空值,避免潜在的类型报错。
内容的提问来源于stack exchange,提问作者ABpositive
相关产品推荐
相关产品推荐

