【发布时间】:2021-03-22 23:30:30
【问题描述】:
我需要将一个特定值更改为我的状态中的一个嵌套对象,所以我想用旧状态 + 需要更改的新值来克隆状态。
我的状态是这样的:
{
"startDate": "2020-12-04T00:00:00.000Z",
"endDate": "2022-12-04T00:00:00.000Z",
"yearlySummary": [
{
"year": "11/2020-11/2021",
"data": {
"actualUsage": 0,
"actualUsagePayment": 0,
"actualFixedFee": 57600,
"actualTotalPayment": 57600,
"pricePerUnit": 110.39999999999999,
"forecastUsagePayment": 500,
"totalUsage": 500,
"totalPayment": 500,
"remainingUsagePayment": 0,
"remainingFixedFee": 0,
"remainingTotalPayment": 0
}
},
{
"year": "11/2021-11/2022",
"data": {
"actualUsage": 0,
"actualUsagePayment": 0,
"actualFixedFee": 57600,
"actualTotalPayment": 57600,
"pricePerUnit": 110.39999999999999,
"forecastUsagePayment": 300,
"totalUsage": 300,
"totalPayment": 300,
"remainingUsagePayment": 0,
"remainingFixedFee": 0,
"remainingTotalPayment": 0
}
}
],
"total": {
"actualUsage": 0,
"actualUsagePayment": 0,
"actualFixedFee": 115200,
"actualTotalPayment": 115200,
"pricePerUnit": 220.79999999999998,
"forecastUsagePayment": 800,
"totalUsage": 800,
"totalPayment": 800,
"remainingUsagePayment": 0,
"remainingFixedFee": 0,
"remainingTotalPayment": 0
}
}
我需要使用 onChange 函数从 inputField 中更改 3 个键的值: 预测使用支付, 剩余使用付款, 总使用量
所以我的输入字段如下所示:
data.yearlySummary.map((year, index) => (
<input
className={classes.input}
name="forecastUsagePayment"
key={index}
onChange={(e) => handleChange(e, index)}
value={year.data.forecastUsagePayment}
/>
))
onChange 函数应该是什么样子的?
到目前为止,我得到的只有这个:
const handleChange = (e, index) => {
const { name, value } = e.target;
setData((prevData) => ({
...prevData,
// What should come next?
}));
};
【问题讨论】:
-
您应该获取对象的副本,更改字段,然后将状态对象设置为复制的对象
-
我知道我应该做什么,只是不太确定该怎么做。
标签: reactjs react-hooks state