


What are the new features in React 16? Introduction to new features and functions of react16
Sep 11, 2018 pm 04:05 PMThis 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(一個(gè)針對(duì)動(dòng)畫效果的API)
New features
-?Fragments:render函數(shù)可以返回?cái)?shù)組和字符串 -?error?boundaries:錯(cuò)誤處理 -?portals?:支持聲明性地將子樹渲染到另一個(gè)DOM節(jié)點(diǎn) -?custom?DOM?attributes?:ReactDom允許傳遞非標(biāo)準(zhǔn)屬性 -?improved?server-side?rendering:提升服務(wù)端渲染性能
-
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 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)
-
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
-
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>???//錯(cuò)誤
-
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); ????????} ????)
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);//渲染一些沒有被正確清理的東西
And you need:
ReactDOM.render(<App />,?p); ReactDOM.unmountComponentAtNode(p); p.innerHTML?=?'nope'; ReactDOM.render(<App />,?p);?//?Now?it's?okay
View 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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
