简体   繁体   English

带有单选按钮的 React 组件重新渲染将值设置回 null

[英]React component with radio buttons re-renders setting the value back to null

I am rendering a questionnaire page that shows a question component that has the following attributes;我正在呈现一个问卷页面,该页面显示了一个具有以下属性的问题组件; Question number, Question text, and 5 radio buttons that each have an answer.问题编号、问题文本和 5 个单选按钮,每个按钮都有答案。

What i am trying to achieve is when a user clicks on a radio button, I store on state the answer and the question number.我想要实现的是当用户单击单选按钮时,我将答案和问题编号存储在 state 上。

I have come across a problem where once my component renders and I click an answer it seems like it re-renders and my radio button of choice seems like it has not been clicked.我遇到了一个问题,一旦我的组件呈现并单击答案,它似乎会重新呈现,而我选择的单选按钮似乎没有被单击。

This is my Questionaire page where I embed the question component这是我嵌入问题组件的问卷页面

  const Questionaire = (props) => {

  const [answers, set_answers] = useState({});

  console.log("Inside Questionaire component", answers);

  const onChangeAnswerFunc = (answer, match) => {
    set_answers({ ...answers, [match.params.questionNumber]: answer });
  };

  return (
    <div className="quiz">
      <Route
        path="/dashboard/questions/:questionNumber"
        component={({ match }) => (
          <Question
            questionNumber={match.params.questionNumber}
            answerFunc={(e) => onChangeAnswerFunc(e, match)}
          />
        )}
      />
    </div>
  );
};

export default Questionaire;

And this is my question component这是我的问题部分

const Question = ({ omat, pmat, cmat, questionNumber, answerFunc }) => {
  const [currentRadioValue, setRadioValue] = useState(null);
  useEffect(() => {
    if (currentRadioValue != null) {
      answerFunc(currentRadioValue);

      console.log("Inside useEffect");
    }
  }, [currentRadioValue, answerFunc]);

  const onChange = (e) => {
    setRadioValue(e.target.value);
    // handleChange();
    // console.log("onChange");
  };
  console.log("Under on change", currentRadioValue);

  const handleChange = () => {
    answerFunc(currentRadioValue);
  };

  // console.log(currentRadioValue);

  const onSubmit = async (e) => {
    e.preventDefault();
  };

  if (!omat) return null;
  const question = omat[questionNumber];
  const {
    question: text,
    section,
    subject,
    score0,
    score25,
    score50,
    score75,
    score100,
  } = question;

  const anyQuestion = (
    <Link to={`/dashboard/questions/${Number(questionNumber) + 1}`}>Next</Link>
  );
  const finalQuestion = <button>Submit</button>;

  const previousQuestion = (
    <Link to={`/dashboard/questions/${Number(questionNumber) - 1}`}>
      Previous
    </Link>
  );

  return (
    <div>
      <div className="questions">
        <h2 className="lead">Question number: {questionNumber} / 40 </h2>
        <p className="question-section">Section: {section}</p>
        <p className="question-subject">Subject: {subject}</p>
        <div>{text}</div>
        <form className="form" onSubmit={(e) => onSubmit(e)}>
          <div className="form-group">
            <>
              <input
                type="radio"
                name={`Radio`}
                value="Radio - 1"
                checked={currentRadioValue === `Radio - 1`}
                onChange={(e) => onChange(e)}
              />
              <label> - {score0}</label>
            </>
          </div>
          <div className="form-group">
            <>
              <input
                type="radio"
                name={`Radio`}
                value="Radio - 2"
                checked={currentRadioValue === `Radio - 2`}
                onChange={(e) => onChange(e)}
              />
              <label> - {score25}</label>
            </>
          </div>
          <div className="form-group">
            <>
              <input
                type="radio"
                name={`Radio`}
                value="Radio - 3"
                checked={currentRadioValue === `Radio - 3`}
                onChange={(e) => onChange(e)}
              />
              <label> - {score50}</label>
            </>
          </div>
          <div className="form-group">
            <>
              <input
                type="radio"
                name={`Radio`}
                value="Radio - 4"
                checked={currentRadioValue === `Radio - 4`}
                onChange={(e) => onChange(e)}
              />
              <label> - {score75}</label>
            </>
          </div>
          <div className="form-group">
            <>
              <input
                type="radio"
                name={`Radio`}
                value="Radio - 5"
                checked={currentRadioValue === `Radio - 5`}
                onChange={(e) => onChange(e)}
              />{" "}
              <label> - {score100}</label>
            </>
          </div>
        </form>
      </div>
      {Number(questionNumber) > 0 ? previousQuestion : null}
      {Number(questionNumber) !== 5 ? anyQuestion : finalQuestion}

      <Link to={`/`}>Exit</Link>
    </div>
  );
};

const mapStateToProps = (state) => ({
  auth: state.auth,
  omat: state.questions.omat,
  pmat: state.questions.pmat,
  cmat: state.questions.cmat,
});

export default connect(mapStateToProps)(Question);

If I disable the handleChange function from the onChange, the radio - button are displayed properly (checked), with the handleChange uncommended the value once passed returns again to null.如果我从 onChange 禁用了handleChange function,则单选按钮将正确显示(选中),并且不加注释的 handleChange 传递的值再次返回到 null。

I will attach a console log which might help further.我将附上一个控制台日志,这可能会有所帮助。

Chrome console log Chrome 控制台日志

Here is a picture of the front end rendered这是前端渲染的图片

Front end前端

Thanks in advance!提前致谢!

Use shouldComponentUpdate life-cycle method to prevent unnecessary rendering, by default component re-rendered on state change.使用shouldComponentUpdate生命周期方法来防止不必要的渲染,默认情况下组件在 state 更改时重新渲染。

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

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