简体   繁体   English

性能比较this.setState(this.state)与this.setState({})

[英]Performance comparison this.setState(this.state) vs this.setState({})

I have a scenario in which I get data from api. 我有一个从api获取数据的场景。 In this case my componentWillReceiveProps() gets triggered whenever I get new value from store. 在这种情况下,每当我从商店获取新值时,都会触发我的componentWillReceiveProps()。

componentWillReceiveProps(newProps){
   if(newProps.listOne){
     this.state.listOne = newProps.listOne;
   }
   if(newProps.listTwo){
     this.state.listTwo = newProps.listTwo;
   }

   this.setState(this.state);

}

Now as per react doc it is inappropriate to use this.setState(this.state); 现在,根据反应文档,不适合使用this.setState(this.state);

So keeping that in mind the way to update state would be 因此请记住,更新状态的方法是

componentWillReceiveProps(newProps){
   if(newProps.listOne){
     this.setState({listOne : newProps.listOne});
   }
   if(newProps.listTwo){
     this.setState({listTwo : newProps.listTwo});
   }

}

In Case 1 my Render gets triggered only once after I have copied all the data to state. 在案例1中,我将所有数据复制到状态后,我的渲染仅被触发一次。 In case 2 my render(and all intermediate life cycles) get triggered, each time my If condition gets fulfilled. 在情况2中,每次满足条件时,都会触发我的渲染(和所有中间生命周期)。

So I don't understand how it improves my performance. 所以我不明白它如何提高我的表现。 Lets say we are talking about not one but lot of conditional update of state. 可以说,我们谈论的不是状态更新,而是状态更新。

If you want to call setState only once, you can do it like this: 如果您只想调用setState一次,则可以这样进行:

componentWillReceiveProps(newProps) {
   // Copy the state instead of mutating this.state directly.
   const state = { ...this.state };

   if (newProps.listOne) {
      state.listOne = newProps.listOne;
   }

   if (newProps.listTwo) {
      state.listTwo = newProps.listTwo;
   }

   this.setState(state);
}

You can further improve here by using truly immutable data structures by means of libraries such as Immuable.js. 您可以通过诸如Immuable.js之类的库使用真正的不可变数据结构来进一步改进。

However, manually batching updates like this isn't necessary from a performance point of view; 但是,从性能的角度来看,不需要像这样手动分批更新。 React internally batches these updates already since this is a lifecycle hook. 由于这是生命周期挂钩,因此React已经在内部批处理了这些更新。 It might make sense if you want to use the callback from setState , though. 不过,如果您想使用setState的回调,可能会很有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM