在本文中,我们将带你了解功能组件中的shouldComponentUpdate在这篇文章中,我们将为您详细介绍功能组件中的shouldComponentUpdate的方方面面,并解答功能组件是什么常见
在本文中,我们将带你了解功能组件中的shouldComponentUpdate在这篇文章中,我们将为您详细介绍功能组件中的shouldComponentUpdate的方方面面,并解答功能组件是什么常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义、javascript – Animated.Component / createAnimatedComponent(Component)如何与Component不同?、org.hibernate.tuple.component.PojoComponentTuplizer的实例源码、react 如何通过 shouldComponentUpdate 来减少重复渲染。
本文目录一览:- 功能组件中的shouldComponentUpdate(功能组件是什么)
- AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义
- javascript – Animated.Component / createAnimatedComponent(Component)如何与Component不同?
- org.hibernate.tuple.component.PojoComponentTuplizer的实例源码
- react 如何通过 shouldComponentUpdate 来减少重复渲染
功能组件中的shouldComponentUpdate(功能组件是什么)
我有一个关于React的问题shouldComponentUpdate
(未覆盖时)。我确实更喜欢纯功能组件,但是即使prop /
state不变,我也担心它每次都会更新。所以我正在考虑使用PureComponent类。
我的问题是:功能组件shouldComponentUpdate
是否与PureComponents 具有相同的检查?还是每次都会更新?
答案1
小编典典在React中,功能组件是无状态的,并且它们没有生命周期方法。 无状态组件是一种编写React组件的优雅方式,而我们的捆绑包中没有太多代码。
但是在内部,无状态组件被包装在一个类中,而目前没有进行任何优化。这意味着无状态组件和有状态组件在内部都具有相同的代码路径(尽管我们对它们的定义不同)。
但是在将来,React可能会优化无状态组件,如下所示:
将来,通过避免不必要的检查和内存分配,我们还将能够针对这些组件进行性能优化。[更多阅读…]
shouldComponentUpdate
您可以在此处应用我们的自定义优化,避免不必要的组件重新渲染。下面说明了此方法在不同类型的组件中的用法:
- 功能性无状态组件
如前所述,无状态组件没有生命周期方法,因此我们无法使用进行优化shouldComponentUpdate
。但是它们已经以不同的方式进行了优化,与具有所有生命周期挂钩的组件相比,它们具有更简单,更优雅的代码结构,并且字节数更少。
- 扩展React.PureComponent
从 React v15.3.0开始 ,我们有了一个新的基类, PureComponent
以扩展为PureRenderMixin
内置类。在引擎盖下,此方法将当前道具/状态与内的下一个道具/状态进行浅层比较shouldComponentUpdate
。
也就是说,我们仍然不能依靠PureComponent
类来将组件优化到所需的水平。如果我们的道具具有Object
类型(数组,日期,普通对象),则会发生这种异常情况。这是因为比较对象时我们遇到了这个问题:
const obj1 = { id: 1 };const obj2 = { id: 1 };console.log(obj1 === obj2); // prints false
因此,浅浅的比较不足以确定情况是否已更改。但是PureComponent
如果您的道具只是字符串,数字,布尔值..而不是对象,请使用class。如果您不想实现自己的自定义优化,也可以使用它。
- 扩展React.Component
考虑上面的例子;如果我们知道对象已更改(如果对象id
已更改),则可以通过比较来实现自己的自定义优化obj1.id ===obj2.id
。在这里我们可以使用extend
普通的Component
基类并shouldComponentUpdate
用来自己对特定键进行比较。
AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义
如何解决AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义?
我想使用@ViewChild从父组件访问子组件功能,但显示“未定义”错误。
我正在尝试实现ngx-infinite-scroll,将滚动应用于父AppComponent,并且当用户向下滚动到底部(滚动)时会触发父AppComponent中的“ onScroll”功能。
因此,“ onScroll”切换了子组件中的ngx-spinner的可见性,并且从api提取所有数据并通过子组件开始进行渲染。
请帮助!!!
父组件: AppComponent
儿童组件: .// current / posts / post-card / post-card.component
PARENT-> AppComponent.ts
import { Component,ViewChild} from ''@angular/core'';
import {PostCardComponent} from ''./current/posts/post-card/post-card.component'';
@Component({
selector: ''app-root'',templateUrl: ''./app.component.html'',styleUrls: [''./app.component.css'']
})
export class AppComponent
{
@ViewChild(PostCardComponent) child: PostCardComponent ;
constructor(){}
onScroll(){
console.log("----scrolled-----");
this.child.showSpinner();
}
}
儿童-> PostCardComponent
import { Component,OnInit} from ''@angular/core'';
import { DomSanitizer } from ''@angular/platform-browser'';
import {Title} from "@angular/platform-browser";
import { HttpClient } from ''@angular/common/http'';
import { NgxSpinnerService } from ''ngx-spinner'';
@Component({
selector: ''app-post-card'',templateUrl: ''./post-card.component.html'',styleUrls: [''./post-card.component.css'']
})
export class PostCardComponent implements OnInit {
received = ''none'';
posts: any = [];
constructor(private http: HttpClient,public spinner: NgxSpinnerService){}
ngOnInit(){
this.loadInitPosts();
}
public showSpinner(){
this.spinner.show();
}
loadInitPosts(){
const url = ''http://localhost/api/getPosts.PHP;
this.http.get(url).subscribe(data => {
this.posts = data;
this.received=''success'';
},error =>
{
this.received=''error'';
});
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
javascript – Animated.Component / createAnimatedComponent(Component)如何与Component不同?
有一些修改对于在一个地方打破动画的setNativeProps做了一些修改,假设因为一些动画相关信息没有被正确传递.
因此,了解createAnimatedComponent如何改变初始组件的问题,添加什么?如果没有正确传递,会导致动画破坏?
如果您知道可能导致此问题,请提供想法/详细答案.
UPDATE
关于这个问题的突破变化发生在this file年的某个地方,参考innerRef传递下来的ref,isTag函数检查它是否是一个本机组件.
解决方法
animatable components can be animated. View,Text,and Image are already provided,and you can create custom ones with createAnimatedComponent. These special components do the magic of binding the animated values to the properties,and do targeted native updates to avoid the cost of the react render and reconciliation process on every frame. They also handle cleanup on unmount so they are safe by default.
https://facebook.github.io/react-native/docs/animated.html
org.hibernate.tuple.component.PojoComponentTuplizer的实例源码
static Object makeCaller ( Object tpl,Object getters ) throws NoSuchMethodException,InstantiationException,illegalaccessexception,InvocationTargetException,NoSuchFieldException,Exception,ClassNotFoundException { PojoComponentTuplizer tup = Reflections.createWithoutConstructor(PojoComponentTuplizer.class); Reflections.getField(AbstractComponentTuplizer.class,"getters").set(tup,getters); ComponentType t = Reflections.createWithConstructor(ComponentType.class,AbstractType.class,new Class[0],new Object[0]); Reflections.setFieldValue(t,"componentTuplizer",tup); Reflections.setFieldValue(t,"propertySpan",1); Reflections.setFieldValue(t,"propertyTypes",new Type[] { t }); TypedValue v1 = new TypedValue(t,null); Reflections.setFieldValue(v1,"value",tpl); Reflections.setFieldValue(v1,"type",t); TypedValue v2 = new TypedValue(t,null); Reflections.setFieldValue(v2,tpl); Reflections.setFieldValue(v2,t); return Gadgets.makeMap(v1,v2); }
static Object makeCaller ( Object tpl,v2); }
static Object makeCaller ( Object tpl,v2); }
static Object makeCaller ( Object tpl,v2); }
react 如何通过 shouldComponentUpdate 来减少重复渲染

在 react 开发中,经常会遇到组件重复渲染的问题,父组件一个 state 的变化,就会导致以该组件的所有子组件都重写 render,尽管绝大多数子组件的 props 没有变化
render 什么时候会触发
首先,先上一张 react 生命周期图:
这张图将 react 的生命周期分为了三个阶段:生成期、存在期、销毁期,这样在 create、props、state、unMount 状态变化时我们可以清楚的看到 reacte 触发了哪些生命周期钩子以及什么时候会 render。
如果我们需要更改 root 的一个 state,使绿色组件视图更改
如果你写过 vue,你会发现组件更新是如上图那样的(视图指令已编译为修改视图的函数存放在绑定的 state 里的属性里,所以能够做到靶向修改),而 react 会以组件为根,重新渲染整个组件子树,如下图(绿色是期望的 render 路径,橙色是无用 render):
所以在 react 里,我们探讨的 render 性能优化是 react 调用 render 的路径如下:
如何避免这些不必要的 render:
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
使用 shouldComponentUpdate () 以让 React 知道当前状态或属性的改变是否不影响组件的输出,默认返回 ture,返回 false 时不会重写 render,而且该方法并不会在初始化渲染或当使用 forceUpdate () 时被调用,我们要做的只是这样:
shouldComponentUpdate(nextProps, nextState) {
return nextState.someData !== this.state.someData
}
但是,state 里的数据这么多,还有对象,还有复杂类型数据,react 的理念就是拆分拆分再拆分,这么多子组件,我要每个组件都去自己一个一个对比吗??不存在的,这么麻烦,要知道我们的终极目标是不劳而获 -_-
React.PureComponent
React.PureComponent 与 React.Component 几乎完全相同,但 React.PureComponent 通过 props 和 state 的浅对比来实现 shouldComponentUpate ()。如果对象包含复杂的数据结构,它可能会因深层的数据不一致而产生错误的否定判断 (表现为对象深层的数据已改变视图却没有更新)
关注点:
- 无论组件是否是 PureComponent,如果定义了 shouldComponentUpdate (),那么会调用它并以它的执行结果来判断是否 update。在组件未定义 shouldComponentUpdate () 的情况下,会判断该组件是否是 PureComponent,如果是的话,会对新旧 props、state 进行 shallowEqual 比较,一旦新旧不一致,会触发 update。
- 浅判等 只会比较到两个对象的 ownProperty 是否符合 Object.js() 判等,不会递归地去深层比较 --- 源码
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x: mixed, y: mixed): boolean {
// SameValue algorithm
if (x === y) { // Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Added the nonzero y check to make Flow happy, but it is redundant
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA: mixed, objB: mixed): boolean {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== ''object'' || objA === null ||
typeof objB !== ''object'' || objB === null) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A''s keys different from B.
for (let i = 0; i < keysA.length; i++) {
if (
!hasOwnProperty.call(objB, keysA[i]) ||
!is(objA[keysA[i]], objB[keysA[i]])
) {
return false;
}
}
return true;
}
- 至于复杂数据结构,用 Object.key () 获取下 key,然后 key 和对应的 value 都是基础类型数据,就是算是简单数据结构,不然就是复杂
针对以上规则我们在项目开发种可以做出如下优化:
尽量将复杂类型数据(ArrayList)所关联的视图单独拆成 PureComonent 有助于提高渲染性能,比如表单、文本域和复杂列表在同一个 render () 中,表单域的输入字段改变会频繁地触发 setState () 从而导致 组件 重新 render ()。而用于渲染复杂列表的数据其实并没有变化,但由于重新触发 render (),列表还是会重新渲染。
react-immutable-render-mixin
我想复杂数组没变化时也不要 render (), 那你用 react-immutable-render-mixin,来,我们看看插件的介绍:
Users are urged to use PureRenderMixin with facebook/immutable-js. If performance is still an issue an examination of your usage of Immutable.js should be your first path towards a solution. This library was created from experimentations with Immutable that were ultimately erroneous; improper usage of Immutable.js . Users should be able to achieve maximum performance simply using PureRenderMixin.
译:不能以正确的姿势来使用 immutable-js 做优化,你就不要瞎折腾了,用它 react-immutable-render-mixin 就行了
它和 ProComponent 原理一样,唯一的区别就是新旧数据的对比,react-immutable-render-mixin 用了 immutable-js 的 is () 方法去做对比,性能强,复杂类型数据也能对比(这里不对 immutable-js 做讨论,一篇很不错的文章 Immutable 详解及 React 中实践), 相比于 React.PureComponent 更方便 --- 源码
import Immutable from ''immutable'';
const is = Immutable.is.bind(Immutable);
export default function shallowEqualImmutable(objA, objB) {
if (objA === objB || is(objA, objB)) {
return true;
}
if (typeof objA !== ''object'' || objA === null ||
typeof objB !== ''object'' || objB === null) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A''s keys different from B.
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
for (let i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
用法很多,我喜欢 Decorator:
import React from ''react'';
import { immutableRenderDecorator } from ''react-immutable-render-mixin'';
@immutableRenderDecorator
class Test extends React.Component {
render() {
return <div></div>;
}
}
今天关于功能组件中的shouldComponentUpdate和功能组件是什么的讲解已经结束,谢谢您的阅读,如果想了解更多关于AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义、javascript – Animated.Component / createAnimatedComponent(Component)如何与Component不同?、org.hibernate.tuple.component.PojoComponentTuplizer的实例源码、react 如何通过 shouldComponentUpdate 来减少重复渲染的相关知识,请在本站搜索。
本文标签: