簡體   English   中英

帶有單選按鈕的 React 組件重新渲染將值設置回 null

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

我正在呈現一個問卷頁面,該頁面顯示了一個具有以下屬性的問題組件; 問題編號、問題文本和 5 個單選按鈕,每個按鈕都有答案。

我想要實現的是當用戶單擊單選按鈕時,我將答案和問題編號存儲在 state 上。

我遇到了一個問題,一旦我的組件呈現並單擊答案,它似乎會重新呈現,而我選擇的單選按鈕似乎沒有被單擊。

這是我嵌入問題組件的問卷頁面

  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;

這是我的問題部分

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);

如果我從 onChange 禁用了handleChange function,則單選按鈕將正確顯示(選中),並且不加注釋的 handleChange 傳遞的值再次返回到 null。

我將附上一個控制台日志,這可能會有所幫助。

Chrome 控制台日志

這是前端渲染的圖片

前端

提前致謝!

使用shouldComponentUpdate生命周期方法來防止不必要的渲染,默認情況下組件在 state 更改時重新渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM