react memo 可以来解决 函数组在传入的props不变是会重新弄渲染的问题,相当与class组件中的PureComponent和shouldComponentUpdate,它可以帮助我们重新渲染页面
const ToBeBetterComponent = React.memo(function MyComponent(props) {
// only renders if props have changed
})
它是主要来渲染函数组件的,而不是来渲染类组件的
import React from 'react';
export default class extends React.Component {
constructor(props){
super(props);
this.state = {
date : new Date()
}
}
componentDidMount(){
setInterval(()=>{
this.setState({
date:new Date()
})
},1000)
}
render(){
return (
<div>
<Child seconds={1}/>
<div>{this.state.date.toString()}</div>
</div>
)
}
}
我们看上面的组件会每秒被渲染一次,但是我们肯定不能够让child 组件每秒钟都渲染一次,所以对于类组件来说我们可以用到PrueComponent
class Child extends React.PureComponent {
render(){
console.log('I am rendering');
return (
<div>I am update every {this.props.seconds} seconds</div>
)
}
}
现在的话就不会出现child 都会渲染一次的情况了。
但是PrueCOmponent 是用于类组件的对与函数组件我们该怎末办呢,所哟我们就出现了React.memo()
React.memo()可接受2个参数,第一个参数为纯函数组件,第二个参数用于对比props控制是否刷新的,与shouldComponentUpdate(0功能类似。
import React from "react";
function Child({seconds}){
console.log('I am rendering');
return (
<div>I am update every {seconds} seconds</div>
)
};
function areEqual(prevProps, nextProps) {
if(prevProps.seconds===nextProps.seconds){
return true
}else {
return false
}
}
export default React.memo(Child,areEqual)