简体   繁体   中英

How to update react state object array

I need to know how to update the array of users inside the state to accept a new user object.

The state users array contains id and name only.

When i try to use update addon to push an item in the users array.

var newUser = {id:1, name:'Foo'};
let newState = update(this.state, {users: {$push: [newUser]}});

"react-dom.js:17858 Uncaught Error: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of UsersTable .(…)"

You are mutating state. Instead try:

const users = this.state.users
users.push(newUser)
this.setState(Object.assign({}, this.state, { users }}))

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