React.PureComponent
React.PureComponent
类似于 React.Component
。它们的不同之处在于React.Component
没有实现 shouldComponentUpdate()
,但是 React.PureComponent
实现了它。采用对属性和状态用浅比较的方式。
import React, { Component, PureComponent } from 'react';
import PropTypes from 'prop-types';
class App extends Component {
constructor(props) {
super(props);
this.state = {number: 0}
}
add = () => {
this.setState({
number: 0
})
}
componentDidUpdate () {
console.log('组件更新')
}
render() {
return (
<div>
<span>{this.state.number}</span>
<button onClick={this.add}>+</button>
</div>
);
}
}
export default App;
如果React组件的 render()
函数在给定相同的props
和state
下渲染为相同的结果,在某些场景下你可以使用 React.PureComponent
来提升性能。
import React, { Component, PureComponent } from 'react';
import PropTypes from 'prop-types';
class App extends PureComponent {
constructor(props) {
super(props);
this.state = {number: 0}
}
add = () => {
this.setState({
number: 0
})
}
componentDidUpdate () {
console.log('组件更新')
}
render() {
return (
<div>
<span>{this.state.number}</span>
<button onClick={this.add}>+</button>
</div>
);
}
}
export default App;
React.memo
React.memo
是一个高级组件. 它和React.PureComponent
类似,只是在函数组件使用,而不是类组件
import React, { Component, PureComponent } from 'react';
import PropTypes from 'prop-types';
class App extends Component {
constructor(props) {
super(props);
this.state = {number: 0}
}
add = () => {
this.setState({
number: 0
})
}
render() {
return (
<div>
<MyButton2 number={this.state.number}></MyButton2>
<button onClick={this.add}>+</button>
</div>
);
}
}
let MyButton2 = React.memo(MyButton)
function MyButton (props) {
console.log('组件更新')
return <span>{props.number}</span>
}
export default App;