You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React父组件向子组件传递questionAnswerPair时出现undefined问题

问题核心原因
  • Props命名不匹配:父组件调用QuestionAnswer子组件时,传递题目的属性名是parentToChild,但子组件解构参数时接收题目的变量名是currentQuestionAnswerPair,二者名称不一致,子组件自然无法拿到对应值,输出为undefined。
  • 循环赋值逻辑错误:你在for循环中多次调用setCurrentQuestionAnswerPair,React状态更新是批量异步执行的,循环结束后状态只会保留最后一个questionAnswerPair的值,前面的所有赋值都会被覆盖。
修复步骤
  1. 修正Props命名,将父组件的子组件调用代码修改为:
<QuestionAnswer 
  currentQuestionAnswerPair={currentQuestionAnswerPair} 
  childToParent={childToParent}
/>
  1. 修正子组件useEffect依赖,确保props变化时同步更新本地状态:
useEffect(() => {
  console.log(currentQuestionAnswerPair)
  setQuestionAnswer(currentQuestionAnswerPair)
}, [currentQuestionAnswerPair]) // 新增依赖项
  1. 优化逐题遍历逻辑(可选,解决当前只能显示最后一题的问题):
    新增当前题号的状态控制,代替直接在循环里批量赋值:
// 父组件新增状态
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:36:04