开发者问题收集

使用 React Hooks 来操控状态,

2020-12-11
75

我需要将一个特定值更改为状态内的嵌套对象,因此我想使用旧状态 + 需要更改的新值来克隆状态。

我的状态如下所示:

{
    "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 个值: forecastUsagePayment、 remainingUsagePayment、 totalUsage

因此我的输入字段如下所示:

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?
    }));
  };
1个回答

这是 React 中一个相当常见的问题,更新状态,尤其是当它们有嵌套数据时

你可以稍微思考一下并找到解决方案,但我理解你的想法

你的句柄更改函数应该是这样的

const handleChange = (e, index) => {
    const { name, value } = e.target;
    const yearlySummaryCopy = [...data.yearlySummary];
    yearlySummaryCopy[index].data[name] = value;
    setData((prevData) => ({
      ...prevData,
      yearlySummary: yearlySummaryCopy
    }));
  };

这里的数据变量是你存储状态的变量.... 如果你使用的是基于类的组件,你可以这样说.state.data

你也可以在 https://codesandbox.io/s/great-hugle-4fuby?file=/src/App.js:1449-1730

检查代码沙箱
Grape JUICE
2020-12-11