【发布时间】:2021-01-30 10:10:03
【问题描述】:
我正在制作决策树,而我的 const responses 曾经是一个数组,但如果我需要删除或添加一个对象,我的 jumpToQuestion 会弄乱所有响应并变得不对齐。所以,我想我可以使我的数组成为一个对象,其中包含对象和一些数组,并且响应可以通过 id 链接而不是数组放置来跳转。我刚刚为我的所有回复分配了 ID。我只知道我的配置是否正确。
PS 并不是我所有的回复都在这里,所以没有那么多代码。
const responses = {
id: 1,
questionText: "Is the account data entry?",
answerOptions: [
{ answerText: "No", isCorrect: false },
{ answerText: "Yes", isCorrect: true, jumpToQuestion: 6 },
],
notes: [
],
id: 2,
questionText: "Is this customer 1 or 2?",
answerOptions: [
{ answerText: "No", isCorrect: false },
{ answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
],
notes: [
],
id: 3,
questionText: "Is the caller",
answerOptions: [
{ answerText: "Power of Attorney/Conservator", isCorrect: true, jumpToQuestion: 15 },
{ answerText: "Lawyer", isCorrect: true, jumpToQuestion: 13 },
{ answerText: "Emergency Responder", isCorrect: true, jumpToQuestion: 14 },
{ answerText: "Wanting to make a payment", isCorrect: true, jumpToQuestion: 14 },
{ answerText: "None", isCorrect: false },
],
notes: [
],
}
const [currentQuestion, setCurrentQuestion] = useState(1);
const handleAnswerButton = (jumpToQuestion) => {
const nextQuestion = jumpToQuestion || currentQuestion + 1;
setCurrentQuestion(nextQuestion);
}
return (
<div className="App">
<div className="appWrapper">
<div className="headerContainer">
<div className="alderlogo">
<img src={Logo} alt="Logo" />
</div>
<div class="vl"></div>
<h1 className="headerName">Verification Procedure</h1>
</div>
<button className="backBtn"><i class="fas fa-arrow-left fa-2x"></i></button>
<h2>{responses[currentQuestion].questionText}</h2>
<div className="answerSection">
{responses[currentQuestion].answerOptions.map((answerOption) => (
<button onClick={() => { handleAnswerButton(answerOption.jumpToQuestion) }}>{answerOption.answerText}</button>
))}
</div>
<div class="hl"></div>
<div className="notesContainer">
{responses[currentQuestion].notes.map((notePoints) => (
<li>{notePoints.note}</li>
))}
<h3>{responses[currentQuestion].addnotes}</h3>
</div>
</div>
</div>
);
}
【问题讨论】:
标签: arrays reactjs object use-state