So I have an array of items that are randomly displayed:
const questions = this.state.questions
.sort(() => Math.random() - Math.random())
.find(() => true);
And I have a button. If I click on this button, I want to put the content of the displayed item:
{questions && (
<div>
<div className="questions-card">
{questions.question}
</div>
<div>
<Button
onClick={() =>
this.setState({
question: questions.question,
})
}
>
Answer
</Button>
</div>
</div>
)}
I don't know why, but every time I click on this button, it skips to the next item. I don't want this. All I want is to put questions.question
in the state. What's going on?
So this is happening because page rerenders each time you click on a button.
See more here:
ReactJS - Does render get called any time "setState" is called?
The problem was this line:
.sort(() => Math.random() - Math.random())
So had to sort it randomly on the back-end side, MongoDB in my case:
let questions = await Question.aggregate([
{ $sample: { size: 1000 } },
]);
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.