我有一个包含对象数组的状态。我一直在尝试更新数组中对象的属性。
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,
}),
]);
};
首先,正确使用状态:
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;
});
}