简体   繁体   中英

Updating all objects in array with UseState in React

What am I doing wrong here?

I'm starting with this:

const [notificationList, setNotificationList] = useState([]);

The array is then populated. Afterwards I want to update every single object in that array... but not working.

setNotificationList(notificationList.map(notif => { ...notif, isRead: true }))

I think it's obvious but I need to sleep.

You have a syntax error. If you run the code, you should see it in the console.

// this is the usual "old" syntax
function() {
  return true
}
// this is the es6 arrow function
() => {
  return true
}
// this is the es6 arrow function without braces
() => true

As you can see here, you can omit {} in an arrow function. However, if you want to return an object, you have to be explicit otherwise the engine doesn't understand_

// not what you want
() => { key: 'value' }
// what you want
() => ({ key: 'value' })

solution:

setNotificationList(notificationList.map(notif => ({ ...notif, isRead: true })))

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