乐趣区

关于前端:react函数组件使用Reactmemo避免重复渲染

在 react 的类组件里,咱们能够通过 shouldComponentUpdate 来被动管制组件是否须要渲染, 那么在函数组件里,有没有相似的办法能够让咱们被动管制组件渲染呢?有的,那就是 React.memo。

React 官网文档给出的介绍:

Class components can bail out from rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.

类组件在应用了 pureComponent 或 shouldComponent 的时候会防止渲染。你当初能够通过应用 React.memo 包裹组件来实现同样的成果。
const MyComponent = React.memo(function MyComponent(props) {/* only rerenders if props change */});

基于此做了个函数封装:MemoComponent

import React, {useState} from "react";
import isEqual from "react-fast-compare";

/**
 * 默认比拟办法
 * 使用者能够自行实现 compare 办法
 * @param {*} prepProps 
 * @param {*} nextProps 
 * @returns 
 */
function defaultCompareFunc(prepProps, nextProps) {
    try {return isEqual(prepProps, nextProps);
    } catch (error) {console.warn("compare error", error);
    }
    return false;
}

function Container(props) {const { RenderItem, ...otherProps} = props;
    return <RenderItem {...otherProps} ></RenderItem>
}

/**
 * 
 * @param {*} component 要缓存的组件
 * @param {*} compare 缓存的办法, 不传则应用默认比拟办法
 * @returns 
 */
function MemoComponent(component, compare = defaultCompareFunc) {const memoComponent = React.memo(component, compare);
    return (props) => {
        return <Container
            RenderItem={memoComponent}
            {...props} >
        </Container>
    }
}

export default MemoComponent;

个别应用办法

import React from "react"
import MemoComponent from "memoComponent"

function Component(props){
    return (<div>Hello World</div>)
}

const componentWithMemo = MemoComponent(Component);
export default componentWithMemo;

联合 dva 应用办法:

import React from "react"
import MemoComponent from "memoComponent"

function Component(props){
    return (<div>Hello World</div>)
}

export default connect(({Component, loading}) => ({
    Component,
    loading: loading,
}))(MemoComponent(Component));
退出移动版