2017-10-12 952 views

回答

1

当从组件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-reconciliationhttps://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578(特别是所谓的(PureComponent和shouldComponentUpdate)

这也是理解之间会发生什么区别有用的部分时,渲染功能被称为与和解的算法确实更新DOM什么。更多关于这个here

0

根据定义,this.setState导致重新呈现。如果你想改变this.state没有重新呈现,没有什么是来回阻止你在做一个正常的人工分配。

this.setState({name: 'newname'}) //changes this.state with render 
this.state.name = 'newname' //no rerender, but still changes this.state 
+0

是不是使用this.state直接被认为是一个坏习惯?根据React [docs](https://reactjs.org/docs/react-component.html#state): 不要直接改变this.state,因为事后调用setState()可能会替换你制作。将'this.state'视为不可变的。 – Namit

+0

@Namit它是,因为在React世界里,没有必要改变'this.state'没有重投。如果您正在操纵不断变化的数据,但不希望每次都重新渲染数据,那么该数据可能不应该放在'this.state'开头。 – Andrew

相关问题