【react】组件优化02:父子组件传值时是否全局渲染问题优化

场景问题:父组件传给子组件的值,可能会变也可能不会变,为了减少内存消耗,需要到达,当传给子组织值改变时,才重新渲染子组件,否则不渲染子组件,只会部分渲染(变化的)父组件。

关键点:生命周期钩子函数:shouldComponentUpdate(nextProps,nextState)
只需要在shouldComponentUpdate中进行判断下一次传的值是否与本次值一致,在做相应的步骤。

父组件parent.jsx

import React from "react";
import Child from "./chid";

/**
 * 技术例子
 * 
 * 定时器
 * 网络请求
 * 事件监听
 *  在组件被销毁都应得到相应的处理
 * 
 */
const MyAPI = {
    count: 0,
    subscribe(cb) {
        this.intervalId = setInterval(() => {
            this.count += 1
            cb(this.count)
        }, 1000)
    },
    unSubscribe() {
        clearInterval(this.intervalId);
        this.reset();
    },
    reset() {
        this.count = 0;
    }

}

export default class Preant extends React.Component {

    state = {
        count: 0
    }

    componentDidMount() {
        MyAPI.subscribe((currentCount) => {
            this.setState({
                count: currentCount
            })
        })
    }

    componentWillUnmount() {
        MyAPI.unSubscribe();
    }

    render() {
        console.log('parent-->render');
        let num = 1;
        return (
            <div>
                Parent:{this.state.count}
                < Child num={num+this.state.count} />
            </div>
        )
    }
}

子组件child.jsx

import React from "react";

class Child extends React.Component {

//进行判断【关键点】
    shouldComponentUpdate(nextProps, nextState) {
        if (nextProps.num === this.props.num) {
            return false;
        }
        return true;
    }

    render() {
        console.log('child-->render');
        return (
            <div >
                Child:{this.props.num}
            </div>
        );

    }
}
export default Child;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值