Warm tip: This article is reproduced from serverfault.com, please click

javascript- React useState钩子并以多步骤形式提交

(javascript - React useState hook and submit in multi step form)

发布于 2020-11-28 00:10:31

我正在使用React JsonSchema Form创建一个多步骤表单我想每次在页面上单击“下一步”按钮并最终提交时都更新我的状态。仅当按钮的类型为Submit时,React JsonSchema Form才会验证条目。所以我的下一个按钮是提交按钮。

由于表单将有多个问题,因此我的状态是对象数组。由于useState的异步性质,我更新后的状态值不易保存到后端。我应该如何获得最终价值?

当我调试时,可以看到直到上一步的数据。有没有一种方法可以使useState表现得像同步调用一样?

这是完整的代码:

const data = [
  {
    page: {
      id: 1,
      title: "First Page",
      schema: {
        title: "Todo 1",
        type: "object",
        required: ["title1"],
        properties: {
          title1: { type: "string", title: "Title", default: "A new task" },
          done1: { type: "boolean", title: "Done?", default: false },
        },
      },
    },
  },
  {
    page: {
      id: 1,
      title: "Second Page",
      schema: {
        title: "Todo 2",
        type: "object",
        required: ["title2"],
        properties: {
          title2: { type: "string", title: "Title", default: "A new task" },
          done2: { type: "boolean", title: "Done?", default: false },
        },
      },
    },
  },
];

interface IData {
  id: Number;
  data: any
};

export const Questions: React.FunctionComponent = (props: any) => {

  const [currentPage, setCurrentPage] = useState(0);
  const [surveyData, setSurveyData] = useState<IData[]>([]);

  const handleNext = (e: any) => {
    setSurveyData( previous => [
      ...previous,
      {
        id: currentPage,
        data: e.formData,
      },
    ]);

    if (currentPage < data.length) setCurrentPage(currentPage + 1);
    else //Here I want to submit the data
  };

  const handlePrev = () => {
    setCurrentPage(currentPage - 1);
  };

  return (
      <Form
        schema={data[currentPage].page.schema as JSONSchema7}
        onSubmit={handleNext}
      >
        <Button variant="contained" onClick={handlePrev}>
          Prev
        </Button>
        <Button type="submit" variant="contained">
          Next
        </Button>
      </Form>
 );
};
Questioner
user1868744
Viewed
11
lawrence-witt 2020-11-28 08:24:49

我将重构新的状态结构以使用状态的实际值而不是回调值,因为这将允许你在设置后访问整个结构:

  const handleNext = (e: any) => {
    const newSurveyData = [
        ...surveyData,
        {
            id: currentPage,
            data: e.formData
        }
    ];

    setSurveryData(newSurveyData);

    if (currentPage < data.length) {
        setCurrentPage(currentPage + 1);
    } else {
        // submit newSurveryData
    };
  };

附带说明:你还必须考虑以下事实:返回上一页意味着你必须按索引拼接新的调查数据,而不是每次都只在末尾附加新的调查数据。