简体   繁体   English

使用反应钩子实现先前的问题逻辑

[英]Implementing a previous question logic with react hooks

I'm making a pretty simple react quiz app in which you go from question to question via a 'next' button.我正在制作一个非常简单的反应测验应用程序,您可以在其中通过“下一步”按钮从一个问题到另一个问题 go。 Each time the next button is clicked a useState hook (passed as props to onAnswerUpdate) pushes an object with the question's title and the chosen answer to an array named 'answers':每次单击下一个按钮时,一个 useState 钩子(作为道具传递给 onAnswerUpdate)将带有问题标题和所选答案的 object 推送到名为“答案”的数组中:

 const nextClickHandler = (e) => { if(selected === '') { return setError('Please select one option'); } onAnswerUpdate(prevState => [...prevState, { q: data.question, a: selected }]); setSelected(''); if(activeQuestion < numberOfQuestions - 1) { onSetActiveQuestion(activeQuestion + 1); }else... }

I implemented a basic previous button logic whose only function is to return to the previous question but I struggled to find a way to replace the object in the answers array corresponding to the correct question when I change the answer to an already answered question.我实现了一个基本的上一个按钮逻辑,其唯一的 function 是返回上一个问题,但是当我将答案更改为已回答的问题时,我很难找到一种方法来替换与正确问题相对应的答案数组中的 object。 I've tried replacing it using the activeQuestion number as an index to the array (like in the code sample below) and splice method but neither of them worked.我尝试使用 activeQuestion 编号作为数组的索引(如下面的代码示例)和 splice 方法替换它,但它们都不起作用。 Any help will be greatly appreciated.任何帮助将不胜感激。

 const nextClickHandler = (e) => { if(selected === '') { return setError('Please select one option'); } onAnswerUpdate(prevState => [...prevState, answers[activeQuestion] = { q: data.question, a: selected }]); setSelected(''); if(activeQuestion < numberOfQuestions - 1) { onSetActiveQuestion(activeQuestion + 1); } else...

Hook with prevState and an array always drive me crazy... I prefer to use an easier approach.prevState挂钩,数组总是让我发疯......我更喜欢使用更简单的方法。 If you need to replace an element inside an array that is on state, you could write:如果您需要替换 state 上的数组中的元素,您可以编写:

...
let currAnswer = answer;
currAnswer[activeQuestion] = { q: data.question, a: selected };
onAnswerUpdate(currAnswer);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM