简体   繁体   中英

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. 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':

 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. 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. 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. If you need to replace an element inside an array that is on state, you could write:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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