更多技术文章,可以浏览我的github地址,https://github.com/HuYuee/blog
原英文链接
10月23日,React发布了16.6版本,在此版本中带来了一些非常有用的新特性。主要的新特性包括:
React.memo()
React.lazy()
static contextType()
static getDerivedStateFromError()
React.memo()
React.memo() 是能作用在简单的函数组件,类似于React.PureComponent对于class组件的作用。它本质上是一个高阶函数,达到的效果就是,自动帮组件执行shouldComponentUpdate() , 但是只是执行浅比较
Using memo()
使用方式就像高阶函数一样,包装了一层,如下:
const MemoizedComponent = React.memo(function MyComponent(props) {
//_ only rerenders if props change_
});
// for arrow functions
const OtherMemoized = React.memo(props => {
return Memoized Component
}
也能包装已经存在的函数,如下:
const MyComponent = props => This is memorable!!
const Memoized = React.memo(MyComponent)
官网在最后明确提到了一句:
This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs。---- React官网
意思就是说:这个高阶函数存在是作为一种性能优化的方式。不要使用它去纯粹地阻止渲染,否则可能会导致出现bug
React.lazy() and Suspense
通过这个API,我们就可以达到代码分割的效果。代码分割是允许我们去延迟加载我们的import,意味着我们在渲染当前页面的时候去提升当前页面的性能,提高渲染速度。
React.lazy() 和 Suspense 现在暂时还不支持服务器端渲染。如果你想要在服务器端做代码分割,我们仍然推荐使用React Loadable。---- React官网
React.lazy()
React.lazy()允许我们去动态的加载组件。
普通方式引入:
import OtherComponent from './OtherComponent';
import AnotherComponent from './AnotherComponent';
function MyComponent(bool) {
return (
{bool? : }
);
}
动态的加载组件方式:
function MyComponent(bool) {
let Component;
if(bool){
Component = React.lazy(() => import('./OtherComponent'));
}else{
Component = React.lazy(() => import('./AnotherComponent'));
}
return (
);
}
Suspense
如果OtherComponent没有被加载成功,我可以通过使用Suspense这个组件的参数fallback
参数来显示一些类似于加载中的提示内容。如下:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
Loading... }>