在什么情况下,setState()不会导致React Component中的重新渲染?
问题描述:
我知道通常道具或React Component状态的任何变化都会导致它重新渲染,但是什么情况下可以调用setState()
而不会导致重新渲染?在什么情况下,setState()不会导致React Component中的重新渲染?
答
当从组件React.Component
继承时,React将在组件中调用父组件重新呈现或setState时默认调用render()
。但是,如果在React组件中实现了shouldComponentUpdate(),则可以使更新周期短路。如果您只有有限数量的基本值(字符串,数字,布尔值)或使用不可变数据结构的道具时,这非常有用。然后,你可以简单地做这样的事情:
shouldComponentUpdate(nextProps, nextState) {
return nextState.name !== this.state.name // Don't re-render if name is equal
}
shouldComponentUpdate()的默认实现
shouldComponentUpdate(nextProps, nextState) {
return true;
}
也可以从React.PureComponent基本上实现你的道具和浅层比较继承州。
我会推荐以下相关文章进行了较深入的答案: https://reactjs.org/docs/optimizing-performance.html#avoid-reconciliation 和https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578(特别是所谓的(PureComponent和shouldComponentUpdate)
这也是理解之间会发生什么区别有用的部分时,渲染功能被称为与和解的算法确实更新DOM什么。更多关于这个here。
答
根据定义,this.setState
导致重新呈现。如果你想改变this.state
没有重新呈现,没有什么是来回阻止你在做一个正常的人工分配。
this.setState({name: 'newname'}) //changes this.state with render
this.state.name = 'newname' //no rerender, but still changes this.state
是不是使用this.state直接被认为是一个坏习惯?根据React [docs](https://reactjs.org/docs/react-component.html#state): 不要直接改变this.state,因为事后调用setState()可能会替换你制作。将'this.state'视为不可变的。 – Namit
@Namit它是,因为在React世界里,没有必要改变'this.state'没有重投。如果您正在操纵不断变化的数据,但不希望每次都重新渲染数据,那么该数据可能不应该放在'this.state'开头。 – Andrew