简体   繁体   English

React Hooks 延迟 setState 更新导致 function 异常

[英]React Hooks delayed setState updates causing anomalies in function

I am building a Quiz application using React and I am fetching the questions as an array and maintaining the states:我正在使用 React 构建一个测验应用程序,我正在将问题作为数组获取并维护状态:

  1. Array holding all the information about all the questions- statement, options, chosen answer, status(answered, marked for review, unvisited);包含所有问题的所有信息的数组——陈述、选项、选择的答案、状态(已回答、标记为审查、未访问);
  2. object with all information about the current question being displayed object 显示当前问题的所有信息
  3. index of current chosen answer (Among the 4 radio buttons)当前选择答案的索引(在 4 个单选按钮中)

Now the problem is that when I chose an option and click on 'Save and go to next question' the following events are triggered:现在的问题是,当我选择一个选项并单击“保存并 go 到下一个问题”时,会触发以下事件:

  1. Update current question info (new status and chosen answer)更新当前问题信息(新状态和选择的答案)
  2. The array of all questions is updated with the new information for the current question所有问题的数组都更新为当前问题的新信息
  3. Go to next question (Update the state #2 (currentQuestionInformation) with the next question and set #3 to the previously chosen answer for that question (if chosen)) Go 到下一个问题(用下一个问题更新 state #2 (currentQuestionInformation),并将 #3 设置为之前为该问题选择的答案(如果选择))

Now the problem is that it is very important for these events to be triggered in sequence else when we go to the next question even if we have answered it and come back to it the state #3 is not updated properly.现在的问题是,当我们 go 到下一个问题时,即使我们已经回答并返回 state #3 没有正确更新,这些事件按顺序触发是非常重要的。

In my code since I am using react hooks the state updation is asynchronous and I am not getting the right sequence required.在我的代码中,因为我使用的是反应挂钩,所以 state 更新是异步的,我没有得到所需的正确序列。 The next question function is triggered before the array with the information about all questions is updated.在更新包含所有问题信息的数组之前,将触发下一个问题 function。 I read a lot of answers but all of them suggested using the Effect Hook.我读了很多答案,但他们都建议使用 Effect Hook。 But the main problem is I don't have a generalized use case for the setStates.但主要问题是我没有 setStates 的通用用例。 For example I won't go to the next question necessarily after the total array is updated and this is one particular situation where I need to trigger goToNextQuestion() after state #1 is updated.例如,在更新总数组后,我不会 go 到下一个问题,这是一种特殊情况,我需要在 state #1 更新后触发 goToNextQuestion() 。 What should I do to achieve my required goal?我应该怎么做才能达到我要求的目标?

You can have a single useState hook that has an object with all those states.您可以有一个 useState 挂钩,它具有包含所有这些状态的 object。 When updating, you can then update them all at once.更新时,您可以一次更新它们。

const [myState, mySetState] = useState({questions:[],current:{},selected:0}

Then when updating, copy the old value, destructuring it and replace with the new info然后在更新时,复制旧值,解构它并替换为新信息

mySetState({...myState, current:newValue, selected:newSelected})

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

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