react

React v16.6中有什么新功能

2018-12-11  本文已影响92人  张义飞

自React v16.5首次发布以来不到2个月,React团队的优秀人员已经向我们赠送了第101版的React。这个最新版本引入了一些新的API增加React.lazy()React.memo()以及contextType甚至引入了一个新的生命周期方法,getDerivedStateFromError

请记住,这是v16的次要版本,因此,如果您已经使用了所述主要版本的版本,则升级应该提供最少令人头疼的地方。

让我们来看看这些新的功能吧!

React.lazy()

React.lazy()允许您仅在需要渲染时加载组件,即延迟加载。这可以让你减少你的包大小,虽然现在你可以用Webpack这样的东西,但是看到它直接进入React是非常棒的。

// React <= v16.5
import ImmediatelyLoadedComponent from './ImmediatelyLoadedComponent';

// React v16.6+
import { lazy } from 'react';
const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent'));

稍等下,还有更多。您可以结合React.lazy()使用Suspense,并指定一个fallback部分,而动态加载组件加载,将显示。

import { lazy, Suspense } from 'react';
const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent'));

function App() {
  return (
    <Suspense fallback={<div>Please wait while we lazy load...</div>}>
      <LazyLoadedComponent />
    </Suspense>
  );
}

应该减少大量的“加载”样板代码!有关备受期待的React Suspense的更多信息,请查看Dan Abramov在JSConf Iceland 2018上发表的流行演讲

请记住,React.lazy()并且Suspense还没有为服务器端渲染做好准备,但将来可以使用。

React.memo()

当您不需要管理状态时,功能组件很棒,但缺少生命周期方法意味着您无法定义shouldComponentUpdate。如果没有它,您的组件将始终重新呈现。

类似于React.PureComponentReact.memo()是一个更高阶的组件,允许您在函数组件的props相同时跳过重新渲染:

const Component = React.memo(function (props) { });

开箱即用,React.memo()只对道具对象进行浅层比较。如果您需要更高级的东西,可以将比较函数作为第二个参数传递给React.memo()

const Component = React.memo(function (props) { }, (prevProps, nextProps) => {
  // Return true if equal, false if not
});

contextType

Context API。它可以被用到,但不鼓励使用。然后在React v16.3中添加了官方Context API。现在在React v16.6中,更容易在类组件中的任何位置使用上下文:

import React, { Component } from 'react';

const GatorContext = React.createContext('American');

class Alligator extends Component {
  static contextType = GatorContext;

  componentDidMount() {
    const contextValue = this.context;
    // Do some stuff with the context value
  }

  componentWillReceiveProps() {
    const contextValue = this.context;
    // Do some other stuff with the context value
  }

  render() {
    const contextValue = this.context;
    // Conditionally render based on the context value
  }
}

getDerivedStateFromError

进入React v16的一个重要补充是Error Boundaries,它有助于通过处理React渲染方法中的错误来缓解以前的痛点。

除此之外componentDidCatch,React v16.6引入了getDerivedStateFromError生命周期方法。与用于错误日志记录的对应文件不同,getDerivedStateFromError收到错误,并且它会返回更新状态的值:

import React, { Component } from 'react';

class GatorError extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.error) {
      return <div>Something borked :(</div>;
    }
    // If these kids act up, we'll know!
    return this.props.children;
  }
}

类似于React.lazy()getDerivedStateFromError目前无法用于服务器端渲染,未来也是如此。

弃用的Api

另外值得注意的是,你应该注意到v16.6中有一小部分的弃用,特别是如果你想让你的代码库保持整洁,就像React-land中的东西一样:

只有在使用StrictMode组件时,才会显示这些弃用。如果没有,您将不会在日志中看到这些。仍然需要值得注意;)

</article>

原文链接

上一篇 下一篇

猜你喜欢

热点阅读