react hook 学习之React.memo()

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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值