首页 > 解决方案 > 如何更新现有对象

问题描述

我正在尝试使用状态挂钩使用新属性更新数组中的当前对象。包含对象的数组如下所示:

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现在变成了一个对象,而不是一直是一个数组。我做错了什么,我应该如何解决我的问题?提前致谢

标签: reactjsreact-hooks

解决方案


您正在传递一个对象作为初始状态:

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 */



推荐阅读