React.memo
类似于PureComponent,对引用类型的数据进行浅比较,即只会比较引用地址是否一致,对地址里的数据不会进行比较。区别就是一个用的class,一个用的function,两种用法比较:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51// React.PureComponent
export default class MyPureComponent extends React.PureComponent {
render() {
console.log(this.props);
return (
<p>This is {this.props.arrs.toString()}.</p>
);
}
}
// React.memo
const MyMemoComponent = (props) => {
return (
<p>This is {props.arrs.toString()}.</p>
);
};
export default React.memo(MyMemoComponent);
// app.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
arrs: ['1']
};
}
handleChangeArrsValue() {
// MyPureComponent|MyMemoComponent不会重新渲染
const {arrs} = this.state;
arrs.push(Math.random());
this.setState({ arrs });
// MyPureComponent|MyMemoComponent会重新渲染
// const {arrs} = this.state;
// const newArrs = arrs.slice(0).push(Math.random());
// this.setState({ arrs: newArrs });
}
render() {
const { arrs } = this.state;
return(
<button
type="button"
onClick={this.handleChangeArrsValue.bind(this)}
>
点击更新数组值
</button>
<MyPureComponent arrs={arrs} />
<MyMemoComponent arrs={arrs} />
);
}
}
// 参考:https://reactjs.org/docs/react-api.html#reactmemo
React.lazy
可以让你能动态渲染组件,最基础的使用就是在组件A渲染完毕之前,用loading效果展示。用法比较简单,其中Suspense中的fallback可以设置在LazyComponent组件渲染完成前你想要展示的内容,比如一个loading效果等。
1 | // LazyComponent.js |
React.lazy(() => import('./LazyComponent'))这种写法需要添加babel插件,否则会报错,这里使用的是babel7,只要修改对应.babelrc文件。
1 | { |
还有一个注意事项官方文档提到的,lazy|Suspense现在还不能在服务端进行渲染,官方推荐用React Loadable。
Note: React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we still recommend React Loadable. It has a nice guide for bundle splitting with server-side rendering.
static contextType
官方的Context Api在v16.3正式引入,替代了原先的Legacy Context API,在16.6.0版本中增加了contextType,只要将对应的context[如themesContext]赋值给myClass.contextType,这样在任何地方,无论是生命周期还是render方法中都能对其[this.context]进行引用。简单的官方例子。
1 | // theme-context.js |
这里只是简单的展示了用法,更多的资料可以参考官方提供的文档。
static getDerivedStateFromError()
一个新的生命周期,当组件A抛错误时会执行到该生命周期,修改其错误状态,渲染出对应错误提示的组件B。在生命周期componentDidCatch也可以设置状态来展示组件B,但是这个功能将会在未来的版本被废除,所以官方建议如果需要设置状态,在getDerivedStateFromError中设置,而不是componentDidCatch。
同样getDerivedStateFromError也不支持服务端渲染,在后续版本中可以得到支持,只是现在在16.6.0版本中提前发布该生命周期。
Note: getDerivedStateFromError() is not yet available for server-side rendering. It is designed to work with server-side rendering in a future release. We’re releasing it early so that you can start preparing to use it.