例如,我如何更改某个状态中的特定对象,我有这样的数据
const colors= [
{
id: 1,
name: "red",
},
{
id: 1,
name: "green",
},
{
id: 2,
name: "blue",
},
];
const storage = [{
id:2,
name:"64 GB"
},
{
id:2,
name:"128 GB"
]
状态值应该是这样的 [{id:1, name:'red"}, {id:2,name:"128GB"}]
有什么方法可以仅根据 id 更新状态?例如:我需要循环数据,如果state.id === id
它会更新该特定对象。所以在我们的例子中,我需要更新状态,[{id:1, name:'green"}, {id:2,name:"128GB"}]
如果state.id === 1
提前致谢
您可以使用浅拷贝更新对象的数组状态并更改值,如下所示:
import * as React from "react";
export default function App() {
const [colors, setColors] = React.useState([
{
id: 1,
name: "red"
},
{
id: 1,
name: "green"
},
{
id: 2,
name: "blue"
}
]);
const updateState = (id, name) => {
let copy = [...colors];
let color = copy.filter((x) => x.id == id)[0];
if (!color) return;
let index = copy.indexOf(color);
color.name = name;
copy[index] = color;
setColors(copy);
};
return (
<div className="App">
{colors.map((color, index) => (
<>
<p>
{color.id} : {color.name}
</p>
</>
))}
<button
onClick={() => {
updateState(2, "yellow");
}}
>
update
</button>
</div>
);
}
下面是示例代码的可执行形式:https : //codesandbox.io/s/mutable-wildflower-n10ys?file=/src/App.js
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句