Home >Web Front-end >JS Tutorial >What are the new features in React 16? Introduction to new features and functions of react16

What are the new features in React 16? Introduction to new features and functions of react16

寻∝梦
寻∝梦Original
2018-09-11 16:05:553184browse

This article mainly introduces some new features of react16, as well as a detailed function introduction of react16. Let’s take a look at the main content of this article

React 16 update

New js environment requirements

react16依靠Map和Set集合和requestAnimationFrame(一个针对动画效果的API)

New features

- Fragments:render函数可以返回数组和字符串
- error boundaries:错误处理
- portals :支持声明性地将子树渲染到另一个DOM节点
- custom DOM attributes :ReactDom允许传递非标准属性
- improved server-side rendering:提升服务端渲染性能
  1. Fragments

    render() {
      return [
        <li key="A"/>First item</li>,
        <li key="B"/>Second item</li>,
        <li key="C"/>Third item</li>,
      ];
    }

    See API

  2. error boundaries

    Previously, once an error occurred in a component, the entire component tree would It is unmounted from the root node. React 16 fixes this and introduces the concept of Error Boundary, which is translated as "error boundary" in Chinese. When an error occurs in a component, we can capture the error through Error Boundary and handle the error gracefully, such as using Error Boundary. The content replaces the error component. Error Boundary can be regarded as a special React component. It has a new life cycle function componentDidCatch. It can capture errors on itself and its subtrees and handle them gracefully, including reporting error logs and displaying error prompts instead of Uninstall the entire component tree. (Note: It does not capture all runtime errors, such as errors in component callback events. You can think of it as a traditional try-catch statement)

    Practice:

    Abstract checking errors Boundary public component:

    class ErrorBoundary extends React.Component{
        constructor(props){
            super(props);
            this.state=({
                ifError:false
            });
        }
    
        componentDidCatch(err, info) {
            this.setState({ ifError: true })
            console.log(err);
        }
    
        render(){
            if(this.state.ifError){
                return `this or its children has error`;
            }
            return this.props.children
        }
    }

    Create a simple child component containing errors:

    class ErrorComponent extends React.Component{
        render(){
            const str = '123';
            return str.toFixed(2);
        }
    }

    Use error boundary components to wrap components that may go wrong

    class MainShowComponent extends React.Component{
        render(){
            return (
                <p>
                    <ErrorBoundary>
                        <ErrorComponent/>
                    </ErrorBoundary>
                </p>
            )
        }
    }

    When wrapped by error boundary components If an error occurs in a child component, the error component will be replaced with the string: this or its children has error, without causing the entire component tree to be unloaded. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)

  3. Portals

    Portals provides a first-class method to render children to DOM nodes outside the parent component's DOM hierarchy.

    ReactDOM.createPortal(
      child,
      container
    );

    The first parameter (child) is any renderable React child element, such as element, string or fragment. The second parameter (container) is a DOM element.

    Normally, when you return an element from a component's render method, it will be loaded into the DOM as a child of the nearest parent node:

    render() {
      // React mounts a new p and renders the children into it
      return (
        <p>
          {this.props.children}
        </p>
      );
    }

    However, sometimes the child is inserted into Other locations in the DOM that will be useful:

    render() {
      // React does *not* create a new p. It renders the children into `pNode`.
      // `pNode` is any valid DOM node, regardless of its location in the DOM.
      return React.createPortal(
        this.props.children,
        pNode,
      );
    }

    For details on Portals and their event bubbling, see the official website and CodePen examples

  4. custom DOM attributes

    Supports non-standard custom DOM attributes. In previous versions, React would ignore unrecognized HTML and SVG attributes. Custom attributes could only be added in the data-* form. Now it will pass these attributes directly to the DOM. This The change allows React to remove attribute whitelisting, thereby reducing file size. But when the custom attribute passed by the DOM is a function type or event handler type, it will also be ignored by React.

    <p a={()=>{}}></p>   //错误
  5. improved server-side rendering

    Improve server-side rendering performance, React 16's SSR has been completely rewritten, the new implementation is very fast, nearly 3 times the performance React 15 now provides a streaming mode that can send rendered bytes to the client faster.

Breaking changes

  • Scheduling and life cycle changes

    • Calling setState returns null will not update render, which allows you to decide whether to update in the update method.

      this.setState(
          (state)=>{
              if(state.curCount%2 === 0){
                  return {curCount:state.curCount+1}
              }else{
                  return null;
              }
      
          }
      )
    • Calling setState in the render method will always cause an update. Previous versions did not support it, but try not to call setState in render.

    • setState's callback function will be executed immediately after componentDidMount/ componentDidUpdate is executed, not after all components are rendered.

          this.setState(
              (state)=>{
                  if(state.curCount%2 === 0){
                      return {curCount:state.curCount+1}
                  }else{
                      return null;
                  }
      
              },
              ()=>{
                  console.log(this.state.curCount);
              }
          )
  1. ReactDOM.render() and ReactDom.unstable_renderIntoContainer() will return null if called in the life cycle function. So to solve this kind of problem, you can use portals or refs

  2. setState changes:

  3. When two components<A /&gt ; and <B / > When replacement occurs, B.componentWillMount will always be executed before A.componentWillUnmount, and before that, A.componentWillUnmount may be executed in advance.

  4. In previous versions, when changing the ref of a component, the ref and dom would be separated before the component's render method was called. Now, we delay the change of ref until the dom element is changed, and the ref will not be separated from the dom.

  5. It is not safe to re-render the container using other methods than React. This might have worked in previous versions, but we feel this is not supported. We now issue a warning for this case, and you need to use ReactDOM.unmountComponentAtNode to clear your node tree.

    ReactDOM.render(<App />, p);
    p.innerHTML = 'nope';
    ReactDOM.render(<App />, p);//渲染一些没有被正确清理的东西

    And you need:

    ReactDOM.render(<App />, p);
    ReactDOM.unmountComponentAtNode(p);
    p.innerHTML = 'nope';
    ReactDOM.render(<App />, p); // Now it's okay

    View this issue

  6. ##componentDidUpdate lifecycle no longer accepts the prevContext parameter.

  7. Using non-unique keys may result in duplication or loss of subcomponents. Using non-unique keys is not supported and has never been supported, but it was a hard bug before.

  8. Shallow renderer no longer triggers componentDidUpdate() because DOM refs are unavailable. This also makes it consistent with the call to componentDidMount() in previous versions.

  9. Shallow renderer no longer supports unstable_batchedUpdates().

  10. ReactDOM.unstable_batchedUpdates now has only one extra parameter after the callback.

  • The name and path of the single-file browser version have been changed to emphasize the differences between development and production versions

    • react/dist/react.js → react/umd/react.development.js

    • ##react/dist/react.min.js → react/umd/react.production.min .js

    • react-dom/dist/react-dom.js → react-dom/umd/react-dom.development.js

    • react-dom/dist/react-dom.min.js → react-dom/umd/react-dom.production.min.js

  • Rewrite and improve the server Renderer

    • # Server rendering no longer uses markup validation and instead appends to the existing DOM on a best-effort basis, warning about inconsistencies. It also no longer uses empty components and annotations for data feedback properties on each node.

    • There is now an explicit API for server rendering containers. Use ReactDOM.hydrate instead of ReactDOM.render if you are restoring server-rendered HTML. Keep using ReactDOM.render if you're just doing client-side rendering.

  • When an unknown property is passed to a DOM component, React will render it into the DOM if it is a valid value. View the documentation

  • Errors in render and lifecycle functions will unload the entire DOM tree by default. To prevent this, you can add error boundaries at the corresponding locations in the UI.

  • DEPRECATED

    • react-with-addons.js is no longer built, all compatible addons are released separately on npm, If you need them, there are single-file browser versions available.

    • Deprecation in 15.x version has been removed from the core package, React.createClass is now available as create-react-class, React.PropTypes is available as prop-types, React .DOM is used as react-dom-factories, react-addons-test-utils is used as react-dom/test-utils, and shallow renderer is used as react-test-renderer/shallow. See the 15.5.0 and 15.6.0 documentation references.

    This article ends here (if you want to see more, go to the PHP Chinese website

    React User Manual column to learn). If you have any questions, you can leave them below Leave a message with a question.

    The above is the detailed content of What are the new features in React 16? Introduction to new features and functions of react16. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn