reactjs - 更新对象状态数组中的对象属性
问题描述
我有一个包含对象数组的状态。我一直在尝试更新该数组中对象的属性。
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;
});
}
推荐阅读
- php - 为什么我无法连接到另一台服务器上的 beanstalkd?
- c++ - std::condition_variable 在 std::condition_variable::notify_all() 从其他线程之后正确唤醒方式
- python - 为什么在切片 numpy ndarrays 时出现此下溢错误?
- entity-framework-core - 数据存储到 ASP.NET Core 5 MVC 中的关联表
- prolog - 如何从 Prolog 中的列表列表中返回所需的列表
- c++ - 为什么 if-else 语句没有给出预期的输出?
- email - 游击队邮件收件箱 id 输出 24 小时更改
- json - 在 Swift 中解析动态 JSON 模型
- c# - 当我尝试将此对象 p.objPrice 拆箱为整数类型时,我收到一个异常:指定的强制转换无效?
- altair - vega-lite(和 Altair?)中的蜂巢图