今天,就介绍一下pure components, 博主也不知道怎么翻译成中文才正确,就先用英文吧!
这个得创建三个文件: 第一个文件
// PureComponent.js 文件 import React, { PureComponent } from 'react' class PureComp extends PureComponent { render() { console.log("Pure component") return ( <div> Pure Component {this.props.name} </div> ) } } export default PureComp第二个文件
// RegularComponent.js 文件 import React, { Component } from 'react' class RegularComponent extends Component { render() { console.log("This is the Regular component") return ( <div> Regular Component {this.props.name} </div> ) } } export default RegularComponent第三个文件
// ParentComponent.js 文件 import React, { Component } from 'react' import PureComp from './PureComponent' import RegComp from './RegularComponent' class ParentComponent extends Component { constructor(props) { super(props) this.state = { name: "World" } } componentDidMount() { setInterval(() => { this.setState({ name: "World" }) }, 2000) } render() { console.log("*******This is the parent component*********") return ( <div> Parent Component <RegComp name={this.state.name}/> <PureComp name={this.state.name}/> </div> ) } } export default ParentComponent在App.js 文件里
// App.js 文件 import React from 'react'; import './App.css'; import Parentcom from './ParentComponent' function App() { return ( <div className="App"> <Parentcom/> </div> ); } export default App;结果如下: 在Chrome的console里显示: Pure Component 只出现一次
Regular Component: A regular component does not implement the shouldComponentUpdate method. It always returns true by default.
Pure Component: A pure component on the other hand implements shouldComponentUpdate with a shallow props and state comparison.
Shallow Comparison (SC) Primitive Types: a (SC) b returns true if a and b have the same value and are of the same type.
Complex Types: a (SC) b returns true if a and b reference the exact same object.
Pure Component: A pure component implements shouldComponentUpdate with a shallow prop and state comparison. Pure components by preventing unnecessary renders can give you a performance boost certain scenarios.
总结: We can create a component by extending the pureComponent class.
A pureComponent implements the shouldComponentUpdate lifecycle method by performing a shallow comparison on the props and state of the component.
If there is no difference, the component is not re-rendered-performance boost.
It is a good idea to ensure that all the children components are also pure to avoid unexpected behavior.
Never mutate the state. Always return a new object that reflects the new state.
如果觉得不错的话,就用点赞来代替五星好评吧!
