如何设置状态并将其推送到数组?

How can I setState and push to an array?

这是我的状态:

class table extends Component {
  state = {
    arr: [],
    numofSub: 1
  };

我希望通过从我的数据库中获取,将一个对象推送到具有设置状态的 arr, 获取效果很好,我在控制台记录了它,我似乎无法将对象推入数组:

componentWillMount() {
    fetch('/api/items')
      .then(data => data.json())
      .then(inputs => this.setState({ arr: [...inputs] }));

  }

当下一个状态依赖于前一个状态时,建议使用功能setstate版本:

componentWillMount() {
    fetch('/api/items')
      .then(data => data.json())
      .then(inputs => this.setState(state => ({ arr: [state.arr,...inputs] })));
  }

至于在 setstate 之后立即记录更改,您应该在 setState's callback. because setState is asynchronous 中进行,并且在您记录 state 时可能不会更新:

this.setState(state => ({key:value}), () => {
  // this is the callback, its safe to log the updated state
  console.log(this.state);
});