React报错Objects are not valid as a React child,已用map仍未解决
解决React渲染报错:"If you meant to render a collection of children, use an array instead"
你遇到的报错核心原因是:当questions或questions.options未正确加载/不存在时,questions?.options.map会返回undefined,而React不允许将undefined作为子元素渲染。以下是具体修复方案:
具体修改步骤
- 确保映射对象为有效数组:将
questions?.options.map改为(questions?.options || []).map,即使options不存在,也会基于空数组执行映射,返回合法的空数组而非undefined。 - 修复异步状态更新逻辑:
setChecked是异步操作,onSelect中直接使用checked会拿到旧状态,应替换为选中的索引i。 - 添加空值判断:在渲染核心内容前,判断
questions是否存在,避免无效渲染。 - 修复label关联问题:原代码中label的
htmlFor与input的id不匹配,导致点击label无法选中单选框,需统一命名。 - 补全单选框选中状态:给input添加
checked属性,让单选框正确反映当前选中状态。
修改后的完整代码
import React, { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' /** Custom Hook */ import { useFetchQestion } from '../hooks/FetchQuestions.js' import { updateResult } from '../hooks/setResult.js' export default function Questions({ onChecked }) { const [checked, setChecked] = useState(undefined) const { trace } = useSelector(state => state.questions); const result = useSelector(state => state.result.result); const [{ isLoading, serverError}] = useFetchQestion() const questions = useSelector(state => state.questions.queue[state.questions.trace]) const dispatch = useDispatch() useEffect(() => { dispatch(updateResult({ trace, checked})) // eslint-disable-next-line react-hooks/exhaustive-deps }, [checked]) function onSelect(i){ onChecked(i) setChecked(i) dispatch(updateResult({ trace, checked: i})) } if(isLoading) return <h3 className='text-light'>Loading</h3> if(serverError) return <h3 className='text-light'>{serverError || "Unknown Error"}</h3> if(!questions) return null return ( <div className='questions'> <h2 className='text-light'>{questions.question}</h2> <ul key={questions.id}> { (questions.options || []).map((q, i) => ( <li key={i}> <input type="radio" value={false} name="options" id={`q${i}-options`} onChange={() => onSelect(i)} checked={result[trace] === i} /> <label className='text-primary' htmlFor={`q${i}-options`}> {q} </label> <div className={`check ${result[trace] === i ? 'checked' : ''}`}></div> </li> )) } </ul> </div> ) }
内容的提问来源于stack exchange,提问作者Omkar Malji
相关产品推荐
相关产品推荐

