简体   繁体   中英

How to set a property of an array of objects state in useState?

I have a useState like this:

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

And an interface sortedItem:

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

items are:

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

I tried to change sortingType value of the first object in the array(as a simple example):

setSortItems({ ...sortItems, sortItems[0].sortingType:'another_value' });

but it is producing an error

You are trying to set an Object to an Array . You can check out react documentation to learn how to update an array state in the right way

Here my example code:

 const newSortItems = sortItems.map((item, index) => { if (index === 0) { return {...item, sortingType: 'another_value', }; } else { return item; } }); setSortItems(newSortItems);

Solution without using map :

 const newSortItems = [...sortItems]; newSortItems.find((item, index) => index === 0 ).sortingType = 'another_value'; setSortItems(newSortItems);

Another solution, look simpler:

 const newSortItems = [ {...sortItems[0], sortingType: 'another_value' }, ...sortItems.filter((item, index) => index;== 0) ] setSortItems(newSortItems);

You can do it like this.

Create a variable to hold the new sorted array,save the sorted array in the variable

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

set this sorted array to the state

setSortItems(newArray);

You could use the slice method.

setSortItems((state) => [
  {...state[0], sortingType: "value"},
  ...state.slice(1)
]);

PS: Note how I've used the state from the setState callback. This helps you avoid stale closures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM