ReactJS:检查shouldComponentUpdate上的props和state [英] ReactJS: Check props and state on shouldComponentUpdate

查看:116
本文介绍了ReactJS:检查shouldComponentUpdate上的props和state的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查所有属性并说明它们是否已更改,如果有任何更改则返回true,并为所有根组件创建基本组件。

I want to check all properties and state if they are changed, return true if any changed and make a base component for all my root components.

我是想知道它是不是最好的做法,让我的组件变慢。
另外,我所做的总是返回true:

I'm wondering if it won't be the best practice and make my components slow. Also, what I did always returns true:

shouldComponentUpdate: function(newProps, newState) {
    if (newState == this.state && this.props == newProps) {
        console.log('false');
        return false;
    }
    console.log('true');
    return true;
},




  1. 我的代码有什么问题吗?

  2. 我应该检查一下道具和状态中的每个变量吗?

  3. 不会检查里面的对象是否因为它们的大小而变慢? / li>
  1. Is there anything wrong with my code?
  2. Should I check for every variable inside props and state?
  3. Won't check for objects inside them make it slow depending on their size?


推荐答案

中比较道具和状态被认为是最好的做法shouldComponentUpdate 确定你是否应该重新渲染你的组件。

It is considered best practice to compare props and state in shouldComponentUpdate to determine whether or not you should re-render your component.

至于为什么它总是评估为true,我相信你的if语句不是不进行深度对象比较,并将您之前和当前的道具和状态注册为不同的对象。

As for why it's always evaluating to true, I believe your if statement isn't performing a deep object comparison and is registering your previous and current props and state as different objects.

我不知道为什么要检查两者中的每个字段无论如何,因为如果道具或状态没有改变,React甚至不会尝试重新渲染组件,所以 shouldComponentUpdate 方法被调用的意思是必须有的东西改变。 shouldComponentUpdate 可以更好地实现,以检查一些道具或声明更改,并决定是否基于此重新渲染。

I don't know why you want to check every field in both objects anyway because React won't even try to re-render the component if the props or state hasn't changed so the very fact the shouldComponentUpdate method was called means something MUST have changed. shouldComponentUpdate is much better implemented to check maybe a few props or state for changes and decide whether to re-render based on that.

这篇关于ReactJS:检查shouldComponentUpdate上的props和state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆