javascript - Reactjs adding an object to state -
i'm using reactjs populate state.users new member when or signs in.
the following code working
var users = this.state.users; users.push(member); this.setstate({users: users});
but when try wrap in 1 line of code fails
this.setstate({users: this.users.state.push(member)});
when try above error further down in list.jsx
uncaught typeerror: this.props.users.map not function
any idea causing this? i'm thinking when use 1 line solution wrong kind of object passed state?
thank you!
it happens because .push
returns new length (int number), not array,
var data = { users: [] }; data.users = data.users.push(10); console.log(typeof data.users); // number
.push
- return new length property of object upon method called.
you can use .concat
instead of .push
this.setstate({ users: this.state.users.concat(member) });
or
this.setstate({ users: [...this.state.users, member] });
Comments
Post a Comment