且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在React中使用setState()来清空/清除数组的值

更新时间:2023-12-05 13:20:40

setState 是原子的,所以你不能只发出多个setState()调用并期望事情正常工作,你要么必须等待状态到在再次更新之前更新,或者遮蔽实例变量。

setState is atomic, so you can't just issue multiple setState() calls and expect things to work, you either have to wait for the state to update before updating it again, or shadow an instance variable.

选项1:

moo: function() {
  this.setState({
    myarr: []
  }, function() { // called by React after the state is updated
    this.setState({
      myarr: [3]
    });
  });
}

这相当麻烦。另一种选择是使用你需要时发送的真实实例变量。

This is fairly cumbersome. The other option is to use a "real" instance variable that you send over as state at moments when you need to.

选项2:

getInitialState: function() {
  this.mylist = [];
  return {
    myarr: this.mylist
  };
},
...
moo: function() {
  this.mylist = [];
  for(var i=0; i<10; i++) {
    this.mylist.push(i);
  }
  this.setState({ myarr: this.mylist });
}

请记住,更新状态意味着您已更改了需要的组件的某个方面重新渲染,所以如果您不打算重新渲染组件,请不要使用setState,例如清除阵列并重新填充它。单独做这些事情,只有在你完成后才更新状态。

Remember that updating the state means you have changed an aspect of your component that demands a rerender, so don't use setState if you don't intend the component to rerender, like between clearing the array and refilling it. Do that stuff separately, and only update the state once you're done.

选项3:

你也可以通过取出状态值,运行更新,然后重新绑定,而无需构建持久的实例变量来执行此操作:

You could also do this by taking out the state values, running your updates, and then rebinding, without ever building a persistant instance variable:

moo: function() {
  var list = this.state.myarr;
  while(list.length > 0) { list.splice(0,1); }
  for(var i=0; i<10; i++) { list.push(i); }
  this.setState({ myarr: list });
}

净效果是相同的:你只 当您的数据处于某种稳定的配置时更新您的UI,因此如果您认为在渲染之间不止一次地调用 setState(),那就是一个问题:每个 setState()调用可能会触发渲染,连续的 setState()如果你不等待,可以互相覆盖他们先绑定。

The net effect is the same: you only update your UI when your data is in some stable configuration, so if you think you're calling setState() more than once between renders, that's a problem: every setState() call may trigger a render, and consecutive setState() may "override" each other if you don't wait for them to bind first.