【问题标题】:Usestate + Setstate [TypeError: Invalid attempt to spread non-iterable instance.] - React Native Form HandlingUsestate + Setstate [TypeError: Invalid attempt to spread non-iterable instance.] - React Native Form Handling
【发布时间】:2020-07-23 15:48:48
【问题描述】:

我正在尝试通过添加一个名为“计费”的新对象来更新状态。我的初始状态如下所示:

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 将来自 Formik 的数据包含在一个类似于 {"first_name": "", "last_name": ""} 的对象中:

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

如何重组我的状态数组或传播 currentState 以便我可以添加我的计费对象。

【问题讨论】:

    标签: javascript reactjs react-native react-hooks formik


    【解决方案1】:

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

    你需要这样设置:

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

    【讨论】:

      【解决方案2】:

      您试图将一个对象传播到一个数组中,因此出现了错误。确保您的状态中有{} 而不是[],您可以按如下方式进一步清理它:

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

      【讨论】:

        猜你喜欢
        • 2022-12-27
        • 2022-12-02
        • 2022-09-23
        • 2021-11-27
        • 2021-09-24
        • 2020-08-15
        • 2021-05-27
        • 1970-01-01
        • 2017-03-01
        相关资源
        最近更新 更多