我正在尝试使用状态钩子使用新属性更新数组中的当前对象。带有对象的数组如下所示:
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 */
嗨,您可以按照此示例使用 useState 钩子在数组中包含新属性。
import React, {useState} from "react";
export default function UseStateExample() {
const [myData, setMyData] = useState([
{
dataLabels: [
{align: 'left'}
],
name: 'my data',
data: [
{y: 1, name: 'Daryl'},
{y: 2, name: 'Negan'}
]
}
]);
function getChartColors() {
return ["red", "green", "blue"]
}
function clickHandler(event) {
let items = [];
myData[0].data.map((item, index) => {
item.color = getChartColors()[index];
items.push(item);
});
setMyData([
...myData
]);
console.log(myData)
}
return (
<div>
<button onClick={clickHandler}>Update myData and show in Console</button>
</div>
);
}