Ten minutes to show you the new features of React16 and new features of react16
Some time ago, Version 16 of React was released, using the MIT open-source license, and some new features were added.
- Error Boundary
- New return type of the render Method
- Portals
- Supports custom DOM attributes.
- The update will not be triggered when setState is passed in null.
- Better server Rendering
- New packaging policy
- ...
1. Use Error Boundary to process errors
Previously, once a component has an error, the entire component tree will be unmounted from the root node. React 16 fixes this issue and introduces the concept of Error Boundary. When a component fails, we can capture the Error Through Error Boundary and handle the Error elegantly. For example, we can use the content provided by Error Boundary to replace the Error component. Error Boundary can be considered as a special React component. The componentDidCatch Life Cycle Function is added, which can capture errors in itself and the Child tree and perform elegant processing on errors, this includes reporting error logs and displaying error prompts, rather than uninstalling the entire component tree. (Note: it cannot capture all runtime errors, such as errors in component callback events. You can think of it as a traditional try-catch statement)
// Best Practice: Abstract ErrorBoundary into a common Component class import React, {Component} from 'react 'export default class ErrorBoundary extends Component {constructor (props) {super (props) this. state = {hasError: false} componentDidCatch (err, info) {this. setState ({hasError: true}) // sendErrorReport (err, info)} render () {if (this. state. hasError) {return <div> Something went wrong! </Div >}return this. props. children }}
We can use ErrorBoundary to wrap it out of an error-prone component, as shown below:
// Usage render () {return (<div> <ErrorBoundary> <Profile user = {this. state. user}/> </ErrorBoundary> <button onClick = {this. onClick}> Update </button> </div> )}
If the Profile component is incorrect, the <div> Something went wrong </div> provided by ErrorBoundary is used instead of the entire component tree.
2. added the return type for the render method.
In React 16, the render method supports direct return of string, number, boolean, null, portal, and fragments (arrays with key attributes ), this can reduce the DOM level of the page to a certain extent.
// Stringrender () {return 'hello, world'} // numberrender () {return 12345} // booleanrender () {return isTrue? True: false} // nullrender () {return null} // fragments, without a key identifier, the console displays warningrender () {return [<div> hello </div>, <span> world </span>, <p> oh </p>]}
The preceding types can now be returned directly in render. You do not need to wrap a layer of container elements in the outer layer. However, in the returned array type, you need to add a unique and unchanged key value to each element. Otherwise, the console reports a warning.
3. Use createPortal to render the component outside the current component tree
The Portals mechanism provides the most direct way to render a child component outside the DOM tree rendered by the parent component. By default, the React component tree corresponds to the DOM tree. Therefore, components such as Modal and Overlay usually put them on the top layer, however, they may only belong to a child component logically, which is not conducive to the Code Organization of the component. By using createPortal, we can render the component to any DOM node we want, but the component is still within the parent component of React. One feature is that the event generated by the Child component can still be captured by the React parent component, but it is not your parent component in the DOM structure. For component organization and code cutting, this is a good attribute.
// Implement a simple masked layer effect and abstract a general Overlay Component import React, {Component} from 'react '; import ReactDOM from 'react-dom '; export default class Overlay extends Component {constructor (props) {super (props); this. container = document. createElement ('div '); document. body. appendChild (this. container);} componentWillUnmount () {document. body. removeChild (this. container);} render () {return ReactDOM. createPortal (<div className = 'overlay '> <span className = 'overlay-close' onClick = {this. props. onClose }>× </span> {this. props. children} </div>, this. container) }}// the style of the component is as follows. overlay {box-sizing: border-box; position: fixed; top: 50%; left: 50%; width: 260px; height: 200px; margin-left:-130px; margin-top:-100px; padding: 10px; background-color: # fff; outline: rgba (0, 0, 0 ,. 5) solid 9999px ;}. overlay-close {position: absolute; top: 10px; right: 10px; color: red; cursor: pointer ;}
The usage is as follows:
class App extends Component { constructor(props) { super(props); this.state = { overlayActive: false } this.closeOverlay = this.closeOverlay.bind(this); this.showOverlay = this.showOverlay.bind(this); } closeOverlay() { this.setState({ overlayActive: false }) } showOverlay() { this.setState({ overlayActive: true }) } render() { return ( <div className="App"> <div>hello world!</div> {this.state.overlayActive && <Overlay onClose={this.closeOverlay}>overlay content</Overlay>} <button onClick={this.showOverlay}>show</button> </div> ); }}
Effect
4. Supports custom DOM attributes.
In earlier versions, React ignores unrecognized HTML and SVG attributes. Custom Attributes can only be added as data, now it will pass these attributes directly to DOM (This change allows React to remove the attribute whitelist, thus reducing the file size), but some statements are still invalid. For example, when the custom attribute passed by DOM is a function type or event handler, it is still ignored by React.
// Incorrect syntax render () {return (<div a = {() = >{}} onclick = {this. showOverlay >></div>) // Warning: Invalid event handler property 'onclick '. did you mean 'onclick '? // Warning: Invalid value for prop 'A' on <div> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.
Currently, attributes such as class and tabindex can be passed to DOM, but a Warning will still be reported. We recommend that you use standard campoff className and tabIndex.
5. Update Is Not triggered when setState is null.
For example, in a function for selecting a city, when you click a city, the value of newValue may change, or the value of newValue may be the same as that of the original city, if the return value is null, the system can directly avoid triggering updates without causing repeated rendering and does not need to be determined in the shouldComponentUpdate function.
selectCity(e){ const newValue = e.target.value; this.setState((state)=>{ if(state.city===newValue){ return null; } return {city:newValue} }))
Note: currently, the setState callback (the second parameter) will be triggered immediately after componentDidMount/componentDidUpdate, rather than after all components are rendered.
6. Better server-side Rendering
React 16's SSR is completely rewritten, and the new implementation is very fast, with performance nearly three times higher than React 15. Now we provide a stream mode streaming that can send rendered bytes to the client more quickly. In addition, React 16 performs better in hydrating (note: the client re-renders the HTML returned by the server, react 16 does not require the initial rendering of the client to be completely consistent with the rendering result returned by the server, but tries to reuse existing DOM elements as much as possible. No more checksum (Mark verification )! And issue a warning for inconsistency. In general, rendering different content on the server and client is not recommended, but this is also useful in some cases (for example, generating timestamp ).
7. New packaging policy
The process. env check is removed from the new packaging policy.
The size of React 16 is 32% smaller than that of the previous version (30% post-gzip). The reduction in file size is partly due to the change in the packaging method.
react is 5.3 kb (2.2 kb gzipped), down from 20.7 kb (6.9 kb gzipped).react-dom is 103.7 kb (32.6 kb gzipped), down from 141 kb (42.9 kb gzipped).react + react-dom is 109 kb (34.8 kb gzipped), down from 161.7 kb (49.8 kb gzipped).
At last, React 16 adopted the new core architecture React Fiber. The official explanation is that "React Fiber is a re-implementation of core algorithms" and will be further studied later.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.