首页 > 解决方案 > 更新对象状态数组中的对象属性

问题描述

我有一个包含对象数组的状态。我一直在尝试更新该数组中对象的属性。

const [state, setState] = useState([obj = {key: "x"}, obj = {key: "y"}])

我正在尝试创建一个 handleChange 事件来控制输入元素。

到目前为止,我尝试了下面的代码,其中 __index 是我用作标识符的属性。

  const handleChange = (event) => {
    setState((prevState) => [
      ...prevState.filter((otherObj) => otherObj.__index !== obj.__index),
      (obj = {
        ...prevState[obj.__index],
        description: event.target.value,
      }),
    ]);
  };

标签: reactjsreact-hooks

解决方案


一、正确使用状态:

const [state, setState] = useState([
    {key: "x"}
    {key: "y"}
]);

然后复制先前的状态并更新您需要的对象,然后将其作为新状态返回:

const handleChange = (e) => {
  setState((prevState) => {
    // Copy previous state into new state
    const state = [
      ...prevState,
    ];

    // Get the current object by using the id to match the key
    // Could be any other way to find the right object depending on the rest of your code
    const obj = state.find(obj => obj.key === e.currentTarget.id)
    obj.description = e.currentTarget.value;

    return state;
  });
}

推荐阅读