React组件中映射嵌套数组时options属性未定义问题排查
问题:React组件中无法获取prompt的options,console显示undefined
数据集
[ { "id": 1, "text": "hey wut r u doin", "options": [ { "id": 1, "text": "Playing Pokemon", "nextPrompt": 2 }, { "id": 2, "text": "Watching a movie", "nextPrompt": 7 } ] }, { "id": 2, "text": "lol you still play that??", "options": [ { "id": 1, "text": "It's fun!", "nextPrompt": 18 }, { "id": 2, "text": "Just kidding ha ha...", "nextPrompt": 7 } ] } ]
组件代码
function PromptsAndOptions() { const [currentPrompt, setCurrentPrompt] = useState(POA[0].text); return ( <section> <section>{currentPrompt}</section> {console.log(currentPrompt)} <section> {currentPrompt.options && currentPrompt.options.map(({ text }) => ( <button key={currentPrompt.options.id}>{text}</button> ))} </section> </section> ); }
问题原因
你把currentPrompt的初始值设成了POA[0].text,这只是一个字符串,而非完整的prompt对象。字符串本身没有options属性,所以currentPrompt.options必然是undefined。
另外还有两个明显的错误:
- 映射options时,key应该用每个选项自身的
id,而不是currentPrompt.options.id(currentPrompt.options是数组,根本没有id属性) - 后续切换prompt时,你需要更新的是整个对象,而非仅仅文本内容
修复方案
将状态改为存储完整的prompt对象,而非单独的文本:
function PromptsAndOptions() { // 初始值设为完整的第一个prompt对象 const [currentPrompt, setCurrentPrompt] = useState(POA[0]); // 切换prompt的处理函数 const handleOptionClick = (nextPromptId) => { const nextPrompt = POA.find(prompt => prompt.id === nextPromptId); if (nextPrompt) { setCurrentPrompt(nextPrompt); } }; return ( <section> <section>{currentPrompt.text}</section> <section> {currentPrompt.options.map(({ id, text, nextPrompt }) => ( <button key={id} onClick={() => handleOptionClick(nextPrompt)}> {text} </button> ))} </section> </section> ); }
内容的提问来源于stack exchange,提问作者mackenzie414
相关产品推荐
相关产品推荐

