reactjs - 如何更新现有对象
问题描述
我正在尝试使用状态挂钩使用新属性更新数组中的当前对象。包含对象的数组如下所示:
const myData = [
{
dataLabels: [
{
align: 'left'
}
],
name: 'my data',
data: [
{
y: 1,
name: 'Daryl'
},
{
y: 2,
name: 'Negan'
}
]
}
];
而且我不想将颜色属性添加到useState
钩子内的数据对象中。这是我迄今为止尝试过的:
const [ newMyData ] = useState({
...myData,
0: {
...myData[0],
data: myData[0].data.map((item, index) => ({ ...item, color: getChartColors()[index] }))
},
});
但问题是它newMyData
现在变成了一个对象,而不是一直是一个数组。我做错了什么,我应该如何解决我的问题?提前致谢
解决方案
您正在传递一个对象作为初始状态:
const [ newMyData ] = useState([ /* <--- use '[' not '{' */
...myData,
0: {
...myData[0],
data: myData[0].data.map((item, index) => ({ ...item, color: getChartColors()[index] }))
},
] /* <--- same here - use ']' not '}' */ );
更新:
根据您在评论中提出的问题:
const myData = [
{
dataLabels: [
{
align: 'left'
}
],
name: 'my data',
data: [
{
y: 1,
name: 'Daryl'
},
{
y: 2,
name: 'Negan'
}
]
}
];
const myObject = myData[0];
const nextObject = {
...myObject,
data: myObject.data.map((item, index) => ({ ...item, color: getChartColors()[index] }))
}
const [myData, setMyData] = useState([ nextObject ]); /* If you still want this to be an array */
/* OR */
const [myData, setMyData] = useState( nextObject ); /* If you want it to be an object instead */
推荐阅读
- javascript - 如果尚未存在,如何有效地将元素添加/推送到数组
- discord.js - 如何创建“TempMute”命令?
- node.js - 如何使用时间序列数据创建猫鼬模式
- python - 如何将图像直接下载到 bytesIO 变量?
- docker - 如何在 Docker 容器中运行 OpenCL + OpenGL?
- css - 如何使外部事件框动态扩展和空心圆对齐
- python - 没有通用 el refresh_token en txt python-O365
- c++ - 以下 C++ 程序中的运行时错误 SIGTSTP
- c# - 在服务器上启用模拟时 Rotativa 不工作
- c# - .NET 应用程序正在链接 64 位 DLL,而不是我想要的 32 位。为什么?