简体   繁体   中英

How to prevent useState from rerendering the component again?

RadioButton 改变他们的位置

import { nanoid } from 'nanoid';
import React from 'react';

export default function Question(props) {
  const answers = [...props.incorrect_answers, props.correct_answer];

  const [selectedAnswer, setSelectedAnswer] = React.useState();

  function handleChange(event) {
    setSelectedAnswer(event.target.value);
    console.log(event.target.value);
  }
  // Randomize answer of the Question
  function createRandom(arr) {
    let myArr = [...arr];
    let randomizedArr = [];

    while (myArr.length > 0) {
      let randomIndex = Math.floor(Math.random() * myArr.length);
      randomizedArr.push(myArr[randomIndex]);
      myArr.splice(randomIndex, 1);
    }
    return randomizedArr;
  }
  const randomizedArr = createRandom(answers);

  // RadioButton for the answers
  const RadioButton = ({ label, value, onChange }) => {
    return (
      <label>
        <input
          type="radio"
          name="answers"
          value={value}
          checked={selectedAnswer === value}
          onChange={onChange}
        />
        {label}
      </label>
    );
  };

  const answersElements = randomizedArr.map((answer) => {
    return (
      <RadioButton
        key={nanoid()}
        label={answer}
        value={answer}
        onChange={handleChange}
      />
    );
  });

  return (
    <div className="question-row">
      <div className="single-question">{props.question}</div>
      <div className="answers">{answersElements}</div>
    </div>
  );
}

RadioButton 改变他们的位置

When I select a radiobutton answer , React rerender the RaidoButton component and call my Randomize function which randomize the answers. I do not know how to prevent Randomize function from being called after the first time. in the two pictures when I select an answer for the first question, the answers get randomized again, I want to prevent this behavior

This is an XY question .

You need the component to rerender when the state changes (if for no other reason than to update which radio button is checked).

The problem is that you need the randomisation function to run only on the initial load.


Create a state for the randomized array:

const [randomizedArr, setRandomizedArr] = useState([]);

Then populate it in an effect hook with an empty dependency array (so it only runs on the initial load of the component).

useEffect(() => {
    const randomizedArr = createRandom(answers);
    setRandomizedArr(randomizedArr);
}, []); 
const [randomizedArr, setRandomizedArr] = React.useState([]);
  const [selectedAnswer, setSelectedAnswer] = React.useState();

  React.useEffect(() => {
    const answers = [...props.incorrect_answers, props.correct_answer];
    const randomizedArr = createRandom(answers);
    setRandomizedArr(randomizedArr);
  }, [props.incorrect_answers, props.correct_answer]);

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