admin管理员组

文章数量:1320661

I'm using reactjs to populate state.users with a new member when he or she signs in.

The following code is working

var users = this.state.users;
users.push(member);
this.setState({users: users});

But when I try to wrap everything in one line of code it fails

this.setState({users: this.users.state.push(member)});

When I try the above I get an error further down in my list.jsx

Uncaught TypeError: this.props.users.map is not a function

Any idea what is causing this? I'm thinking that when I use the one line solution the wrong kind of object is passed into the state?

Thank you!

I'm using reactjs to populate state.users with a new member when he or she signs in.

The following code is working

var users = this.state.users;
users.push(member);
this.setState({users: users});

But when I try to wrap everything in one line of code it fails

this.setState({users: this.users.state.push(member)});

When I try the above I get an error further down in my list.jsx

Uncaught TypeError: this.props.users.map is not a function

Any idea what is causing this? I'm thinking that when I use the one line solution the wrong kind of object is passed into the state?

Thank you!

Share Improve this question asked Aug 5, 2015 at 10:50 Miguel StevensMiguel Stevens 9,23019 gold badges75 silver badges135 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

It happens because .push returns the new length (int number), not array,

var data = {
    users: []
};

data.users = data.users.push(10);
console.log(typeof data.users); // number

.push - return the new length property of the object upon which the method was called.

You can use .concat instead of .push

this.setState({
   users: this.state.users.concat(member)
});

or

this.setState({
  users: [...this.state.users, member]
});

本文标签: javascriptReactjs adding an object to stateStack Overflow