更新后第二次迭代只能pull/call React Native状态

Can only pull/call React Native state on the second iteration after updating

我有一个更新状态的 Formik 表单。但是,我只能使用再次点击“提交”时的状态。

 onSubmit={(values) => {
          addData(values);
          console.log(data);
        }}>
  const addData = (billing) => {
    setData((currentData) => {
      const shipping = {
        first_name: billing.first_name,
        last_name: billing.last_name,
        address_1: billing.address_1,
        address_2: billing.address_2,
        city: billing.city,
        state: billing.state,
        postcode: billing.postcode,
        country: billing.country,
      };
      const line_items = items;
      return {billing, shipping, line_items, ...currentData};
    });
    console.log(data);
  };

我知道值会更新,因为在我第二次单击之前,如果我注释掉“addData”函数,我仍然可以看到我记录的数据。然而,在我第一次点击“提交”时,这些值没有记录下来。我需要能够在同一个函数中调用这些值,这样我就可以进行 API 调用并将它们推送到数据库。

假设 setData 来自 useState 钩子,它是一个异步函数,所以它不会立即更新值。

解决该问题的一种方法是使用 useEffect 挂钩并监听数据变量的变化,但在这里它不会起作用,因为您需要在另一个函数中使用它。

您可以通过如下更改流程来解决。

 const addData = (billing) => {
  const shipping = {
    first_name: billing.first_name,
    last_name: billing.last_name,
    address_1: billing.address_1,
    address_2: billing.address_2,
    city: billing.city,
    state: billing.state,
    postcode: billing.postcode,
    country: billing.country,
  };
  const line_items = items;
  const updatedData = { billing, shipping, line_items, ...data };

  setData(updatedData);
  console.log(updatedData);

  return updatedData;
};

这将更新状态以及 return 您可以在提交函数中立即使用的值。

onSubmit={(values) => {
  const updateData=   addData(values);
  console.log(updateData);
}}>