Usestate + Setstate [TypeError: Invalid attempt to spread non-iterable instance.] - React Native Form Handling
Usestate + Setstate [TypeError: Invalid attempt to spread non-iterable instance.] - React Native Form Handling
我正在尝试通过添加一个名为“billing”的新对象来更新状态。我的初始状态如下所示:
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",
},
});
然而,当我 运行 这个函数时,我得到一个类型错误,说我无法传播状态。 Billing 在一个对象中包含来自 Formik 的数据,如下所示 {"first_name": "", "last_name": ""}
:
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});
我正在尝试通过添加一个名为“billing”的新对象来更新状态。我的初始状态如下所示:
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",
},
});
然而,当我 运行 这个函数时,我得到一个类型错误,说我无法传播状态。 Billing 在一个对象中包含来自 Formik 的数据,如下所示 {"first_name": "", "last_name": ""}
:
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});