美文网首页
react-native中统计组件渲染次数

react-native中统计组件渲染次数

作者: nextChallenger | 来源:发表于2020-04-15 11:55 被阅读0次

    性能优化的很大一个点就是避免组件重复渲染。
    在react中有很多统计组件重复渲染的工具,但是react-native中经常不能使用。
    所以此处介绍一种自己统计渲染次数的方法

    实现思路:

    通过给组件的某个方法添加修饰器,统计该方法的调用次数。

    弊端:

    方法的调用次数,需要reload代码后,才会重新技术。原因是修饰器是编译阶段就替换了目标方法,所以统计次数的变量,此时初始化完成。除非reload代码,不然该变量不会重置。

    修饰器代码:
    export function callTimes(target, name, descriptor) {
        if (!target) {
            return;
        }
        if (!target.constructor) {
            return;
        }
        // 保存旧的方法
        const oldValue = descriptor.value;
        let times = 0;
        descriptor.value = function() {
            // 输出日志
            // eslint-disable-next-line no-console
            console.log(`[${target.constructor.name}] Calling [${name}] times:`, ++times);
            return oldValue.apply(this, arguments);
        };
        return descriptor;
    }
    
    使用:
    export default class Example extends PureComponent {
        state = { num: 0 };
    
        componentDidMount() {
            this.load();
        }
    
        load = async () => {
            const res = await this.requestData();
            this.setState({ num: res });
        };
    
        requestData = () => {};
    
        @callTimes
        render() {
            const { num } = this.state;
            return (
                <View>
                    <Text> textInComponent {num} </Text>
                </View>
            );
        }
    }
    

    然后打开debug模式在chrome查看日志即可。

    参考资料:
    js修饰器及其实际用途

    相关文章

      网友评论

          本文标题:react-native中统计组件渲染次数

          本文链接:https://www.haomeiwen.com/subject/ofzqvhtx.html