React 16 new features

Source: Internet
Author: User
Tags deprecated file size min set set versions

September 26, 2017 react 16 released, learn about the new features through our official website and examples. React 16 Update New JS Environment requirements

React16 relies on the map and set set and Requestanimationframe (an animation-effect-oriented API)
new Features
-The Fragments:render function can return an array and a string
-error boundaries: Fault handling
-portals: Supports the declarative rendering of subtrees to another DOM node
-Custom Dom Attributes:reactdom allow non-standard properties to be passed
-improved server-side rendering: Improves service-side rendering performance

Fragments

Render () {
  return [
    <li key= "A"/>first item</li>,
    <li key= "B"/>second item</li
    <li key= "C"/>third item</li>,
  ];
}

See API

Error boundaries

Previously, once a component had an error, the entire component tree would be unmount from the root node. React 16 fixes this and introduces the concept of error boundary, which is translated into "wrong bounds", and we can catch errors and gracefully handle errors by error boundary when a component fails, such as using error The content provided by boundary overrides the error component. The error boundary can be seen as a special react component, with the addition of the Componentdidcatch life cycle function, which captures errors on its own and subtree and gracefully handles errors, including escalation of error logs, presentation of error hints, rather than unloading the entire component tree. (Note: It does not capture all runtime errors, such as errors in a component callback event, which can be imagined as a traditional try-catch statement)

Practice:

Abstract out check error boundary common components:

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 it children has error ';
        }
        Return This.props.children
    }
}

Create a simple sub-component that contains the error:

Class Errorcomponent extends react.component{
    render () {
        const STR = ' 123 ';
        Return str.tofixed (2);
    }
}

Wrapping a component that may be faulted using the error boundary component

Class Mainshowcomponent extends react.component{
    render () {
        return (
            <div>
                <errorboundary >
                    <ErrorComponent/>
                </ErrorBoundary>
            </div>
        )
    }
}

When an error occurs in a subassembly that is wrapped by an error boundary component, the error component is replaced with a string: this or it children has error without causing the overall component tree to be unloaded.

Portals

Portals provides a first-class way to render a descendant to a DOM node outside the DOM hierarchy of the parent component.

Reactdom.createportal (Child
  ,
  container
);

The first argument (child) is any react that can be rendered, such as an element, a string, or a fragment. The second argument (container) is a DOM element.

Typically, when you return an element from a component's Render method, it is loaded into the DOM as a child of the nearest parent node:

Render () {
  ///React mounts a new div and renders the children into it
  return (
    <div>
      {This.props.chi Ldren}
    </div>
  );
}

However, it is sometimes useful to insert children into other locations in the DOM:

Render () {
  //React does *not* create a new div. It renders the children into ' divnode '.
  ' Divnode ' is any valid DOM node, regardless of it in the DOM.
  Return React.createportal (
    this.props.children,
    Divnode,
  );
}

For portals and its event bubbling see the official website and codepen examples

Custom DOM Attributes

Support for nonstandard custom DOM properties, in previous versions, React ignores unrecognized HTML and SVG attributes, custom attributes can only be added by data-* form, and now it passes these properties directly to the DOM, which allows react to remove the attribute whitelist, Thus reducing the file size. However, when the custom property passed by the DOM is a function type or event handler type, it is also ignored by react.

<div a={() =>{}}></div>   //Error

Improved Server-side rendering

Improved service-side rendering performance, React 16 SSR is completely rewritten, the new implementation is very fast, nearly 3 times times the performance of React 15, now provides a flow mode streaming, can be faster to send the bytes rendered to the client. Breaking the Change

Scheduling and life cycle changes Reactdom.render () and Reactdom.unstable_renderintocontainer () will return NULL if called in the life cycle function. So solving this kind of problem can use portals or refs

Changes in SetState:

Calling SetState returns null will not update render, which allows you to decide whether to update yourself 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 always results in an update that was not supported by the previous version, but try not to call SetState in render.

SetState's callback function executes immediately after Componentdidmount/componentdidupdate executes, rather than after all components have been rendered.

    This.setstate (state
        ) =>{
            if (state.curcount%2 = = = 0) {
                return {curcount:state.curcount+1}
            }else {
                return null;
            }

        },
        () =>{
            console.log (this.state.curCount);
        }
    )

When two components <a/> and <b/> are replaced, B.componentwillmount is always executed before A.componentwillunmount, and A.componentwillunmount is likely to be executed ahead of time. Previous versions, when a component's ref was changed, the ref and Dom were detached before the component's Render method was called. Now we delay the change in ref until the DOM element is changed and ref is separated from the DOM.

It is not safe to use other methods to re-render the container without using react. This may take effect in previous versions, but we do not think it is supported. Now we're going to give you a warning, and you need to use Reactdom.unmountcomponentatnode to empty your node tree.

Reactdom.render (<app/>, div);
div.innerhtml = ' nope ';
Reactdom.render (<app/>, div);//render something that has not been properly cleaned

And you need to:

Reactdom.render (<app/>, div);
Reactdom.unmountcomponentatnode (div);
div.innerhtml = ' nope ';
Reactdom.render (<app/>, div); Now it ' s okay

View this issue

The Componentdidupdate life cycle no longer accepts the Prevcontext parameter. The use of a non-unique key may result in the replication or loss of subcomponents, the use of a non-unique key is not supported, and has never been supported, but this is a hard error. Shallow renderer (shallow rendering) no longer triggers componentdidupdate () because the DOM refs is not available. This also makes it consistent with calls in previous versions of Componentdidmount (). Shallow renderer no longer supports unstable_batchedupdates (). Reactdom.unstable_batchedupdates now has only one additional parameter after the callback.

The name and path of the single-file browser version has been changed to emphasize 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

overriding and improving server renderer server rendering no longer uses tag validation, but instead tries to attach to the existing DOM, warning inconsistencies. It also no longer uses the annotations of the blank components and data feedback properties on each node. Rendering the container for the server now has a clear API. Use reactdom.hydrate instead of Reactdom.render if you are recovering the HTML rendered by the server. Continue to use, reactdom.render if you just do client rendering.

When an unknown property is passed to a DOM component, the react is rendered into the DOM if it is a valid value. Viewing a document error in Render and life cycle functions by default, the entire DOM tree is unloaded, and in order to prevent this, you can add an error boundary at the appropriate location in the UI. deprecated No longer builds react-with-addons.js, all compatible plugins are released separately on NPM, and if you need them, you can use a single file browser version. Deprecated in the 15.x release has been removed from the core package, and React.createclass can now act as a create-react-class,react.proptypes as a prop-types,react.dom React-dom-factories,react-addons-test-utils used as react-dom/test-utils, shallow renderer as react-test-renderer/ Shallow use. See 15.5.0 and 15.6.0 documentation reference.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.