我正在尝试通过添加一个名为“ 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",
},
});
但是,当我运行此函数时,出现typeError提示我无法传播状态。帐单将来自Formik的数据包含在一个 {"first_name": "", "last_name": ""}
的对象中:
const addData = (billing) => {
setData((currentData) => {
return [billing, ...currentData];
});
};
如何重组状态数组或扩展currentState以便添加计费对象。
答案 0 :(得分:1)
状态data
是一个对象而不是数组,这就是[billing, ...currentData]
失败的原因。
您需要改为这样设置:
const addData = (billing) => {
setData((currentData) => {
return { billing, ...currentData }; // <<< spread inside an object
});
};
答案 1 :(得分:1)
您正在尝试将对象散布到数组中,因此会出现错误。确保您的状态中没有{}
而不是[]
,可以按照以下说明进一步清除它:
const addData = (billing) => setData((currentData) => {billing, ...currentData});