Home >Backend Development >PHP Tutorial >React v16.3.0: New lifecycles and context API
A few days ago we wrote an article about the upcoming changes to our traditional lifecycle approach, including a step-by-step migration strategy. In React 16.3.0, we've added some new lifecycle methods to aid migration. We've also introduced new APIs for long-running request features: an official context API, a ref forwarding API, and a more semantic ref API.
Please read on to learn more about this release.
For many years, React has provided an experimental API for Context. Although it is a powerful tool, its use is frowned upon due to problems inherent in the API, so we intend to replace this experimental API with a better API.
React 16.3 introduces a new Context API that is more efficient and supports static type checking and deep updates.
NOTE
The old ContextAPI will continue to be retained into React 16.x, so you will have time to migrate.
Here is an example of how to inject a "topic" using the new context API:
## by 司徒正美 const ThemeContext = React.createContext('light'); class ThemeProvider extends React.Component { state = {theme: 'light'}; render() { return ( <ThemeContext.Provider value={this.state.theme}> {this.props.children} </ThemeContext.Provider> ); } } class ThemedButton extends React.Component { render() { return ( <ThemeContext.Consumer> {theme => <Button theme={theme} />} </ThemeContext.Consumer> ); } }
Previously, React provided two ways to manage refs: String ref API and callback ref API. Although the string ref API is more convenient, it has several disadvantages, so our official recommendation is to use callback ref.
React 16.3 provides a new solution for managing refs, which provides convenience for string refs and has no disadvantages:
## by 司徒正美 class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } render() { return <input type="text" ref={this.inputRef} />; } componentDidMount() { this.inputRef.current.focus(); } }
NoteExcept In addition to the new createRef API, callback refs will continue to be supported.
You don't need to replace callback refs in the component. They are slightly more flexible, so they will continue to be an advanced feature.
Higher-order components (or HOCs) are a common way to reuse code between components. Based on the theme context example above, we might create a temporary object with the current "theme" injected as a property:
## by 司徒正美 function withTheme(Component) { return function ThemedComponent(props) { return ( cc08703116ce42022d08955abae73f54 {theme => 6ed8e9073d9c761724eb70bf3f0fade5} bf7c81c161b24597f4bb608217085ce7 ); }; }
We can use the above special way to connect the component to the theme context without having to directly Use topic context. For example:
## by 司徒正美 class FancyButton extends React.Component { buttonRef = React.createRef(); focus() { this.buttonRef.current.focus(); } render() { const {label, theme, ...rest} = this.props; return ( 3f01e199a4239832cc42b335d0472095 {label} 65281c5ac262bf6d81768915a4a77ac0 ); } } const FancyThemedButton = withTheme(FancyButton); // We can render FancyThemedButton as if it were a FancyButton // It will automatically receive the current "theme", // And the HOC will pass through our other props. ad6931a2197aede9d7a61bfc94e4cffa;
HOCs usually pass props to the component they wrap. Unfortunately, the refs didn't penetrate. This means that if we use a FancyThemedButton, we cannot add the ref to the FancyButton and therefore we cannot call focus().
The new proxy API solves this problem by providing a way to intercept a ref and forward it as a normal prop:
## by 司徒正美 function withTheme(Component) { // Note the second param "ref" provided by React.forwardRef. // We can attach this to Component directly. function ThemedComponent(props, ref) { return ( cc08703116ce42022d08955abae73f54 {theme => ( f3d328559b51a9b75ca8e71699437894 )} bf7c81c161b24597f4bb608217085ce7 ); } // These next lines are not necessary, // But they do give the component a better display name in DevTools, // e.g. "ForwardRef(withTheme(MyComponent))" const name = Component.displayName || Component.name; ThemedComponent.displayName = `withTheme(${name})`; // Tell React to pass the "ref" to ThemedComponent. return React.forwardRef(ThemedComponent); } const fancyButtonRef = React.createRef(); // fancyButtonRef will now point to FancyButton f3c9e20fcfb699cb163492c96d8d5bf1;
React’s class component API has been around for many years with little change. However, as we add support for more advanced features, such as error bounds and the upcoming asynchronous rendering mode, we extend this model in ways that it was not originally intended.
For example, in the current API, it is very easy to prevent the initial rendering by using some unusual means. In part, this is because there are so many hooks to accomplish this given task, and it's not clear which one is the best. We have noticed that the interrupt behavior of error handling is often not considered and can lead to memory leaks (this will also affect the upcoming asynchronous rendering mode). The current class component API also complicates other tasks, such as the work of our code optimizer (Prepack).
componentWillMount
, componentWillReceiveProps
, componentWillUpdate
These hooks can easily cause problems and seriously disrupt the React life cycle. For these reasons, we are deprecating these methods in favor of better alternatives.
We recognize that this change will impact many existing components. Therefore, the migration path will be as smooth as possible and migration options will be provided. (At Facebook, we have over 50,000 React components. We also rely on a progressive release cycle!
NOTEDeprecation warnings will be enabled in future versions of React 16 , are retained until 17 is released.
They can still be used even in React17, but they will be prefixed with "UNSAFE_" to indicate that they may cause problems. We have also prepared an automated script for this. Rename them in existing code
In addition to deprecating unsafe lifecycle hooks, we also added some new lifecycle hooks:
getDerivedStateFromProps
Used by componentWillReceiveProps.
##getSnapshotBeforeUpdate, used to safely read properties from the DOM before updating.
< ;StrictMode /> is a tool designed to expose potential problems. Like
20b482145aa8764fe95d208d18a8c1ba,
50449077873ac5e8cb1383836e576ad1 will not. Rendered into a view. It can activate additional checks and warnings for its child components.
Note##8a50a6ab2ed5f48935ba47798a0657e4.Checks are only available in development. mode; they will not affect production builds.
While strict mode may not catch all problems (such as certain types of tampering), it can help a lot of people if you run in strict mode. mode to see warnings, these things are likely to cause asynchronous rendering errors
In version 16.3, StrictMode helps:
Identify components with unsafe lifecycle hooks.
Warning about legacy string ref API usage.
Detect unexpected side effects
##
The above is the detailed content of React v16.3.0: New lifecycles and context API. For more information, please follow other related articles on the PHP Chinese website!