Analysis of new features in React 16.3
Context API is always confusing. This API is official, but the official does not want developers to use this API, saying that this API will change in the future. Now is the time for that change. The new API has been merged. And it looks more "user friendly". Especially when you have to use redux or mobx, you can choose the new Context API to achieve simpler state management.
The new API is very simple to use: React.createContext()
, thus creating two components:
import {createContext} from 'react'; const ThemeContext = createContext({ background: 'yellow', color: 'white' });
Call createContext
The method will return two objects, one is Provider
and the other is Consumer
.
ThatProvider
is a special component. It can be used to provide data to components in a subtree. An example:
class Application extends React.Component { render() { <ThemeContext.Provider value={{background: 'black', color: 'white'}}> <Header /> <Main /> <Footer /> </ThemeContext.Provider> } }
The above example shows how to pass the "theme" context. Of course these values can be dynamic (e.g. based on this.state
).
The next step is to use Consumer
.
const Header = () => { <ThemeContext.Consumer> {(context) => { return ( <p style={{background: context.background, color: context.color}}> Welcome! </p> ); }} </ThemeContext.Consumer> }
If it is not nested in a Provider
when rendering Consumer
. Then the default value set when the createContext
method is called will be used.
Note:
Consumer must have access to the same Context component. If you want to create a new context and use the same input parameters, the data of this new context will not be accessible. Therefore, Context can be regarded as a component. It can be created once, and then exported and imported.
This new syntax uses function as child mode (sometimes also called render prop mode). If you are not very familiar with this model, I recommend you read these articles.
The new API no longer requires you to declare
contextProps
.
The data passed by Context is the same as the value
attribute of the Context.Provider
component. Modifications to Provider
data will cause all consumers to redraw.
New declaration cycle method
Refer to this RFC. New lifecycle methods will be introduced and old ones will be deprecated.
This change is primarily to enforce best practices. You can read this article to understand why these lifecycle methods can get weird. These best modes are very important in React 16's asynchronous drawing mode (Async Mode).
Methods to be deprecated:
componentWillMount
--UsecomponentDidMount
instead ofcomponentWillUpdate
--UsecomponentDidUpdate
instead of##componentWillReceiveProps
--Use a new method:
static getDerivedStateFromPropsinstead.
StrictMode or
AsyncMode, you can use it in this way, but you will receive a warning:
UNSAFE_componentWillMount
UNSAFE_componentWillReceiveProps
UNSAFE_componentWillUpdate
componentWillReceivePropsWe need other ways to update state based on changes in props. The community decided to introduce a new
static method to deal with this problem.
this, and they are modified with the
static keyword in front when they are declared.
this, how to call
this.setState? The answer is,
does not call . This method directly returns the state data that needs to be updated, or returns null if there is nothing to update.
static getDerivedStateFromProps(nextProps, prevState) { if(nextProps.currentRow === prevState.lastRow) { return null; } return { lastRow: nextProps.currentRow, isCrollingDown: nextProps.curentRow > prevState.lastRow } }
this.setState before. Only these returned values will be modified. If they are null, the state will not be modified. All other values of state will be retained.
constructor, or a class attribute. Otherwise, a warning will be reported.
getDerivedStateFromProps() will be called during the first mount and redraw, so you basically don’t need to setState based on the incoming props in the constructor.
. If
is defined, then componentWillReceiveProps
is defined. Then, only the former will be called, and you will receive a warning. Generally you will use a callback to ensure that certain code is not called until the state is updated. Then, please move these codes to
. If you don’t like to use the
keyword, then you can do this: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">ComponentName.getDerivedStateFromProps = (nextProps, prevState) => {
// Your code here
}</pre><div class="contentsignin">Copy after login</div></div>
<h2 id="Static-Mode">Static Mode</h2>
<p>严格模式是一个新的方式来确保你的代码是按照最佳实践开发的。它实际是一个在<code>React.StrictMode
下的组件。它可以用在你的组件树的任何一部分上。
import {StrictMode} from 'react' class Application extends React.Component { render() { return ( <StrictMode> <Context.Provider value={{background: 'black', color: 'white'}}> <Header /> <Main /> <Footer /> </Context.Provider> </StrictMode> ); } }
如果一个在StricMode
子树里的组件使用了componentWillMount
方法,那么你会看到一个报错消息。
AsyncMode
异步模式在React.unsafe_AsyncMode
下。使用AsncMode
也会打开StrictMode
模式下的警告。
相关推荐:
The above is the detailed content of Analysis of new features in React 16.3. 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

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

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.

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

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.

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.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

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

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.
