更新对象状态数组内的对象属性

时间:2020-07-22 09:36:57

标签: reactjs react-hooks

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

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,
      }),
    ]);
  };

1 个答案:

答案 0 :(得分:1)

首先,正确使用状态:

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;
  });
}