【问题标题】:How to set a property of an array of objects state in useState?如何在useState中设置对象数组的属性?
【发布时间】:2022-08-18 23:44:52
【问题描述】:

我有一个这样的 useState:

  const [sortItems, setSortItems] = useState<sortedItem[]>(items);

和一个接口 sortedItem:

interface sortedItem {
  label: string; 
  sortingType: string;
  key: string;
}

项目是:

[{key: \'name\', label: \'Name\', sortingType: \'initial\'},
{key: \'name1\', label: \'Name1\', sortingType: \'initial\'}]

我尝试通过项目映射以更改数组中第一个对象的sortingType 值(作为一个简单的示例):

    sortItems.map((item, index) => {
      if(index === 0)
        setSortItems({ ...sortItems, sortItems[index].sortingType:\'another_value\' });

})

但它正在产生错误

  • 为什么要映射然后在地图内设置数据?
  • 我在一个实际上在地图内调用的函数中设置数据。但为了简单起见将其发布在stackoverflow中,我将其放在地图中

标签: javascript reactjs use-state


【解决方案1】:

你可以这样做。

创建一个变量来保存新的排序数组,将排序数组保存在变量中

const newArray=sortItems.map((item,index)=>{
if(index != 0)return item;
return item.sortingType="another_value";
});

将此排序数组设置为状态

setSortItems(newArray);

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2020-03-29
    • 2020-10-03
    • 2021-07-19
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多