【问题标题】:How can I setState and push to an array?如何设置状态并推送到数组?
【发布时间】:2019-02-26 19:00:08
【问题描述】:

这是我的状态:

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

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

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

  }

【问题讨论】:

  • this.setState({ arr: [...this.state.arr, ...inputs] })
  • 谢谢你的回复,我试过了,当我控制台记录状态时我得到一个空数组,像这样:[]​长度:0​:数组[]

标签: arrays reactjs setstate


【解决方案1】:

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

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

至于在setstate 之后立即记录更改,您应该在setState's callback 中执行此操作。因为setState is asynchronous和登录时可能不会更新state

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

【讨论】:

  • 很好用,我完全忘记了它是异步的,谢谢!
  • @AlexAlex 很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
相关资源
最近更新 更多