【发布时间】: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