


What are the new features in React 16? Introduction to new features and functions of react16
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:提升服务端渲染性能
-
Fragments
render() { return [ <li key="A"/>First item</li>, <li key="B"/>Second item</li>, <li key="C"/>Third item</li>, ]; }
Copy after loginSee API
-
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 } }
Copy after loginCreate a simple child component containing errors:
class ErrorComponent extends React.Component{ render(){ const str = '123'; return str.toFixed(2); } }
Copy after loginUse error boundary components to wrap components that may go wrong
class MainShowComponent extends React.Component{ render(){ return ( <p> <ErrorBoundary> <ErrorComponent/> </ErrorBoundary> </p> ) } }
Copy after loginWhen 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)
-
Portals
Portals provides a first-class method to render children to DOM nodes outside the parent component's DOM hierarchy.
ReactDOM.createPortal( child, container );
Copy after loginThe 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> ); }
Copy after loginHowever, 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, ); }
Copy after loginFor details on Portals and their event bubbling, see the official website and CodePen examples
-
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> //错误
Copy after login -
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; } } )
Copy after login 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); } )
Copy after login
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
setState changes:
When two components
<A /> ;
and<B /
> When replacement occurs, B.componentWillMount will always be executed before A.componentWillUnmount, and before that, A.componentWillUnmount may be executed in advance.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.
-
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);//渲染一些没有被正确清理的东西
Copy after loginAnd you need:
ReactDOM.render(<App />, p); ReactDOM.unmountComponentAtNode(p); p.innerHTML = 'nope'; ReactDOM.render(<App />, p); // Now it's okay
Copy after loginView this issue
- ##componentDidUpdate lifecycle no longer accepts the prevContext parameter.
- 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.
Shallow renderer no longer triggers componentDidUpdate() because DOM refs are unavailable. This also makes it consistent with the call to componentDidMount() in previous versions.
Shallow renderer no longer supports unstable_batchedUpdates().
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
- # 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.
- 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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install
