nextProps 和 NextState 总是等效的

Wri*_*ate 2 javascript reactjs

据我所知,在 shouldComponentUpdate 中使用 nextProps 和 nextState 来根据 this.state.someProperty 与 nextState.someProperty 的比较结果来确定组件是否应该重新渲染。如果它们不同,则组件应该重新渲染。

这很清楚。

然而,事实似乎并非如此。查看此代码。

    class Box extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }

   this.counter = 
     this.counter.bind(this)
  }

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})
    }, 10000);
  }

  componentDidMount() {
    this.counter();
  }

  shouldComponentUpdate(nextProps, nextState) { 
    console.log(this.state.count + " " +  nextState.count)
    return true;
  }

  render() {
    return (
      <div> 
        <h1>This App Counts by the Second </h1>
        <h1>{this.state.count}</h1> 
    </div>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)

在 shouldComponentUpdate 中,我记录了 state.count 和 nextState.count 值,并且它们每次都是相等的。他们不应该有所不同吗?如果不是,如果使用 setState 更改状态确保它们相同,那么检查它们是否等效的目的是什么?

Shu*_*tri 5

nextState 和 currentState 总是相同的,因为你在更新原始状态对象时改变了它

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})  // mutation done here
    }, 10000);
  }
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,你必须使用像这样的函数 setState

counter() {
    setInterval(()=>{
      this.setState(prevState => ({count: prevState.count + 1}))
    }, 10000);
  }
Run Code Online (Sandbox Code Playgroud)