React流程图问题:如何根据选中答案的questionId展示对应问题
React流程图组件问题重构方案
问题背景
我正在React中开发一款流程图组件,页面展示问题及下方的可选答案,选中不同答案时需切换至对应的新问题。目前在传递答案的questionId以展示下一个问题时遇到问题:初始小规模数据下实现正常,但问题数量较多时会出现展示错误问题的情况,已确认questionId与目标问题的id完全匹配,推测是state使用不当或用nextQuestion作为数组索引的方式存在问题(问题流程并非线性,例如问题2的答案可跳转至问题15)。
如何重构代码以实现根据选中答案的questionId展示对应问题?
UI示例(当前更关注逻辑而非视觉效果):
- 默认状态:展示初始问题及对应可选答案按钮
- 选中答案后:切换至目标问题及对应答案按钮
初始代码
import React, { useState } from 'react'; export function Flowchart() { const [nextQuestion, setNextQuestion] = useState<number>(0); const Questions = [ { id: 0, question: 'Question 0', answers: [ { id: 1, answer: 'Go to Question 1', questionId: 1 }, { id: 2, answer: 'Go to Question 2', questionId: 2 } ] }, { id: 1, question: 'Question 1', answers: [ { id: 1, answer: 'Go to Question 0', questionId: 0 }, { id: 2, answer: 'Go to Question 2', questionId: 2 } ] }, { id: 2, question: 'Question 2', answers: [ { id: 1, answer: 'Go to Question 0', questionId: 0 }, { id: 2, answer: 'Go to Question 1', questionId: 1 } ] }, ]; return ( <div className="flowchart__container"> <h1>{chartTitle}</h1> <p>{Questions[nextQuestion].question}</p> {Questions[nextQuestion].answers.map((answer) => ( <button onClick={() => setNextQuestion(answer.questionId)} key={answer.id}> {answer.answer} </button> ))} </div> ); }
问题原因
初始代码直接用nextQuestion作为数组索引获取问题,这种方式仅在问题的id与数组索引完全一致时有效。当问题流程非线性(比如id=15的问题在数组中的索引不是15),就会出现索引不匹配,导致展示错误的问题。
解决方案:使用find()方法匹配问题
通过Array.find()方法根据questionId精准匹配目标问题,无论数组中问题的顺序如何,都能正确找到对应内容。更新后的代码如下:
import React, { useState } from 'react'; export function Flowchart() { const [nextQuestion, setNextQuestion] = useState<number>(0); const Questions = [ { id: 0, question: 'Question 0', answers: [ { id: 1, answer: 'Go to Question 1', questionId: 1 }, { id: 2, answer: 'Go to Question 2', questionId: 2 } ] }, { id: 1, question: 'Question 1', answers: [ { id: 1, answer: 'Go to Question 0', questionId: 0 }, { id: 2, answer: 'Go to Question 2', questionId: 2 } ] }, { id: 2, question: 'Question 2', answers: [ { id: 1, answer: 'Go to Question 0', questionId: 0 }, { id: 2, answer: 'Go to Question 1', questionId: 1 } ] }, ]; // 根据id查找当前问题 const currentQuestion = Questions.find((q) => q.id === nextQuestion); return ( <div className="flowchart__container"> <h1>{chartTitle}</h1> {/* 处理找不到问题的边界情况 */} <p>{currentQuestion ? currentQuestion.question : null}</p> {currentQuestion ? currentQuestion.answers.map((answer) => ( <button onClick={() => setNextQuestion(answer.questionId)} key={answer.id}> {answer.answer} </button> )) : null} </div> ); }
优化说明
- 精准匹配:通过
find()方法根据问题id匹配,彻底解决数组索引与id不匹配的问题,支持任意非线性的问题流程。 - 边界处理:添加了
currentQuestion为空的判断,避免因找不到问题导致的报错。
内容的提问来源于stack exchange,提问作者dcmswim
相关产品推荐
相关产品推荐

