Reactjs 添加一个对象到状态

Reactjs adding an object to state

我正在使用 reactjs 在新成员登录时填充 state.users

以下代码有效

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

但是当我尝试将所有内容都包含在一行代码中时,它失败了

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

当我尝试上述操作时,我在 list.jsx

中进一步出错

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

知道是什么原因造成的吗?我在想,当我使用单行解决方案时,错误类型的对象被传递到状态中了吗?

谢谢!

这是因为.push returns新的长度(整数),而不是数组,

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.

您可以使用 .concat 而不是 .push

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

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