1. memo
介绍React.memo之前,先了解一下React.Component和React.PureComponent。
React允许定义一个class或者function作为组件,那么定义一个组件类,就需要继承React.Component.
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}注意:继承React.Component的React组件类中,render()为必须方法,其他都为可选。
React.PureComponent 和 React.Component类似,都是定义一个组件类。不同是React.Component没有实现shouldComponentUpdate(),而 React.PureComponent通过props和state的浅比较实现了。
如果组件的props和state相同时,render的内容也一致,那么就可以使用React.PureComponent了,这样可以提高组件的性能。
class Welcome extends React.PureComponent { render() { return <h1>Hello, {this.props.name}</h1>; }}当props和state中有复杂数据结果时,不好使用PureComponent,还是要使用Component。
React.memo是一个高阶组件,类似于React.PureComponent,不同于React.memo是function组件,React.PureComponent是class组件。
const MyComponent = React.memo(props => { return ( );});
这种方式依然是一种对象的浅比较,有复杂对象时无法render。在React.memo中可以自定义其比较方法的实现。
memo接收两个参数,一个是组件,一个是函数。这个函数就是定义了memo需不需要render的钩子。
比较前一次的props跟当前props,返回true表示不需要render。
也就是传给Memo的name不变时,不会触发MyComponent的render函数。
function MyComponent(props) { return ( );}function areEqual(prevProps, nextProps) { // 就是判断props的变化对UI的影响 if(prevProps === nextProps) { return true; } return falae;}export default React.memo(MyComponent, areEqual);
2.lazy and suspence
动态导入主要应用场景是延迟加载方法,对于组件来说,并不是很适用,但是React.lazy对于组件的加载则是有比较大的帮助。
注意:目前明确指出,React.lazy和suspense并不适用于服务端渲染
既然是延迟加载,就会有一个加载过程,之前在渲染的时候,基本我们自都是顶一个一个<Loading>组件,然后通过变量控制进行操作,如果加载完成,取消掉则<Loading>组件。
如果直接使用React.lazy,会报错误:需要一个占位符ui,
Suspense使用的时候,fallback一定是存在且有内容的,否则会报错。
代码如下:
import React, { Component, Suspense, lazy } from 'react';const Other1 = lazy(() => import('./other'));const Other2 = lazy(() => new Promise(resolve => setTimeout(() => resolve( // 模拟ES Module { // 模拟export default default: function render() { return <div>Other2 Component</div> } } ), 3000 )));class App extends Component { render() { return ( <div> <h4>一个基本的 lazy 和 suspense 的例子</h4> <Suspense fallback={<div>Other1 Loading...</div>}> <Other1 /> </Suspense> <h4>一个模拟 lazy 和 suspense 的例子</h4> <Suspense fallback={<div>Other2 Loading...</div>}> <Other2 /> </Suspense> </div> ); }}export default App;