Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript nextProps和NextState总是等价的_Javascript_Reactjs - Fatal编程技术网

Javascript nextProps和NextState总是等价的

Javascript nextProps和NextState总是等价的,javascript,reactjs,Javascript,Reactjs,我了解,shouldComponentUpdate中使用了nextProps和nextState,以根据将this.state.someProperty与nextState.someProperty进行比较的结果确定组件是否应重新加载。如果它们不同,组件应重新加载 这是清楚的 然而,目前的情况似乎并非如此。查看此代码 class Box extends React.Component { constructor(props) { super(props); this

我了解,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>
    );
  }
};

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

nextState和currentState始终相同,因为您在更新原始状态对象时对其进行了变异

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})  // mutation done here
    }, 10000);
  }
为了解决此问题,必须使用函数setState,如

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

非常感谢。在您的示例中,在哪里定义prevState变量?它来自哪里?这是从setState传递过来的吗?这个.state.count+1是否也有效?只需从statement@SamiKuhmonen,是的,它可以工作,但建议在基于前一个状态更新当前状态时使用functional setState,以避免任何不一致。这就是我提出上述建议的原因answer@SamiKuhmonen您可以在@WriterState阅读此答案以了解更多详细信息,请查看我的上述评论中的链接以了解其工作原理,并查看setState的文档