嵌套数组中的 onChange react-hook-form 上的值没有改变

问题描述 投票:0回答:1

我想使用 React hook 来处理嵌套数组,这是我的任务。我可以做所有事情,但是当我获得所有正确的值时,状态没有设置在 onChange 上。 这就是我的数组的样子

  const { register, handleSubmit, setValue, getValues } = useForm({
defaultValues: {
  quizData: [{
    pId: 1,
    questions: [{ que: 'QUESTION 1', options: ['option 1', 'option 2'], correctAnswer: 0, selectedAnswer: -1 }, { que: 'QUESTION 2', options: ['option 1', 'option 2'], correctAnswer: 0, selectedAnswer: -1 }]
  }]
}
});

所选答案未更新,下面是代码和框的链接,您可以在那里运行应用程序。

代码沙箱链接

javascript reactjs forms react-hook-form
1个回答
0
投票
import React, { useEffect } from "react";
import { useForm } from "react-hook-form";

function Quiz() {
  const { register, handleSubmit, setValue, getValues } = useForm({
    defaultValues: {
      quizData: [
        {
          pId: 1,
          questions: [
            {
              que: "QUESTION 1",
              options: ["option 1", "option 2"],
              correctAnswer: 0,
              selectedAnswer: -1,
            },
            {
              que: "QUESTION 2",
              options: ["option 1", "option 2"],
              correctAnswer: 0,
              selectedAnswer: -1,
            },
          ],
        },
      ],
    },
  });

  useEffect(() => {
    // Manually set selected values after component mounts
    const data = getValues("quizData");
    data.forEach((p, pIndex) => {
      p.questions.forEach((q, qIndex) => {
        setValue(
          `quizData[${pIndex}].questions[${qIndex}].selectedAnswer`,
          q.selectedAnswer
        );
      });
    });
  }, [getValues, setValue]);

  const handleAnswerChange = (pIndex, qIndex, event) => {
    console.log(pIndex, qIndex, event.target.value);
    const newValue = parseInt(event.target.value);
    setValue(
      `quizData[${pIndex}].questions[${qIndex}].selectedAnswer`,
      newValue
    );
  };

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {getValues("quizData", []).map((p, pIndex) => (
        <div key={p.pId}>
          {p.questions.map((q, qIndex) => (
            <div key={q.que}>
              <h3>{q.que}</h3>
              <select
                {...register(
                  `quizData[${pIndex}].questions[${qIndex}].selectedAnswer`
                )}
                onChange={(event) => handleAnswerChange(pIndex, qIndex, event)}
              >
                <option value={-1}>Select an option</option>
                {q.options.map((option, index) => (
                  <option key={index} value={index}>
                    {option}
                  </option>
                ))}
              </select>
            </div>
          ))}
        </div>
      ))}
      <button type="submit">Submit</button>
    </form>
  );
}

export default Quiz;

尝试这些步骤,看看它们是否有助于解决问题。如果您需要进一步帮助,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.