Javascript 我需要澄清react的状态和生命周期

Javascript 我需要澄清react的状态和生命周期,javascript,reactjs,Javascript,Reactjs,我目前正在学习React,但我不完全理解这是错误的: // Wrong this.setState({ counter: this.state.counter + this.props.increment, }); 这是正确的: // Correct this.setState((state, props) => ({ counter: state.counter + props.increment })); 有人能给我一个现实世界的例子,我可以使用第二种形式的setState

我目前正在学习React,但我不完全理解这是错误的:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});
这是正确的:

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
有人能给我一个现实世界的例子,我可以使用第二种形式的setState来接受一个函数吗

这是

由于this.props和this.state可能会异步更新,因此 不应依赖其值来计算下一个状态

1在大多数情况下,只要不使用当前状态/道具来计算下一个状态,就可以使用此代码段

例如,此代码段仅用于从github获取数据并更新到其状态。我们可以在这个.setState中放置一个对象

class FetchGithub extends react.Component{
  state = {
    //...
  };

  componentDidMount() {
    fetch('https://api.github.com/repos/facebook/react/commits')
      .then(data => this.setState(data.json()))
      .catch(err => this.setState(err));
  }
}
2但是一旦场景是使用当前状态/道具来计算下一个状态,那么您需要放置一个函数来确保当前状态已经得到更新

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
[更新]

因为props是从该组件的父级或redux的还原程序传递的参数,这意味着处理它需要时间。所以你还需要确保道具是最新的

让我们再次看看您的代码示例。应包含两个组件:

父组件,控制+1或-1->AdjustComponent 子组件,仅用于显示结果->显示组件 因此,正确的流程是用户单击+1/-1,调整组件将道具传递到DisplayComponent。然后DisplayComponent通过当前状态和AdjustComponent发送的道具更新其状态。并显示在屏幕上

但是,如果用户很快地点击-1,然后点击+1,或者如果用户的计算机突然有巨大的负载需要处理,这会影响他们的浏览器性能,那该怎么办呢。因此,当您使用此代码段时:

this.setState({
  counter: state.counter + props.increment
});
AdjustComponent尚未收到应为+1的最新props,但DisplayComponent已使用旧的props.increment更新,该props.increment为-1,导致错误结果。

假设您有一个CheckBoxComponent,其状态在构造函数中初始化如下:

this.state={enabled:true}

您希望在用户单击复选框时更新其状态。所以你写了这个点击处理程序:

function toggleCheckbox() {
    this.setState({enabled: ???});
}
这种情况就是第二种设置状态的目的。单击处理程序应编写为:

function toggleCheckbox() {
    this.setState(prevState => ({enabled: !prevState.enabled}));
}

是你投了反对票?我想知道为什么,您至少应该更正您的答案:.thendata=>this.setState{data:data.json}函数中的第二个参数props如何?那是干什么用的?你能再举一个第二参数道具的例子吗?