Home >Web Front-end >JS Tutorial >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
react16依靠Map和Set集合和requestAnimationFrame(一个针对动画效果的API)
- 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>, ]; }
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> //错误
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.
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
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 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!