Usestate+Setstate[TypeError:传播不可迭代实例的尝试无效.]-React Native For



我正试图通过添加一个名为"的新对象来更新状态;计费";。我的初始状态如下:

const [data, setData] = useState({
    payment_method: 'bacs',
    payment_method_title: 'Direct Bank Transfer',
    set_paid: true,
    line_items: [
      {
        product_id: 93,
        quantity: 2,
      },
    ],
  });

在我添加表单数据后,我希望它看起来像这样:

const [data, setData] = useState({
    payment_method: 'bacs',
    payment_method_title: 'Direct Bank Transfer',
    set_paid: true,
    line_items: [
      {
        product_id: 93,
        quantity: 2,
      },
      {
        product_id: 22,
        variation_id: 23,
        quantity: 1,
      },
    ],
    shipping_lines: [
      {
        method_id: 'flat_rate',
        method_title: 'Flat Rate',
        total: 10,
      },
    ],
 billing: {
        first_name: "John",
        last_name: "Doe",
      },
  });

然而,当我运行这个函数时,我得到一个typeError,说我不能传播状态。Billing在一个看起来像 {"first_name": "", "last_name": ""}:的对象中包含来自Formik的数据

  const addData = (billing) => {
    setData((currentData) => {
      return [billing, ...currentData];
    });
  };

如何重组我的状态数组或分散currentState,以便添加我的计费对象。

您的状态data是对象而不是数组,这就是[billing, ...currentData]失败的原因。

你需要这样设置:

const addData = (billing) => {
  setData((currentData) => {
    return { billing, ...currentData };  // <<< spread inside an object
  });
};

您正试图将对象扩展到数组中,因此出现错误。确保你的状态中有{}而不是[],你可以按照以下方式进一步清洁:

const addData = (billing) => setData((currentData) => {billing, ...currentData});

最新更新