Home > Web Front-end > JS Tutorial > Analysis of new features in React 16.3

Analysis of new features in React 16.3

小云云
Release: 2018-02-09 15:36:45
Original
4314 people have browsed it

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'
});
Copy after login

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: &#39;black&#39;, color: &#39;white&#39;}}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  }
}
Copy after login

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>
}
Copy after login

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--Use componentDidMount instead of

  • componentWillUpdate--Use componentDidUpdate instead of

  • ##componentWillReceiveProps--Use a new method: static getDerivedStateFromProps instead.

But this won’t happen immediately, they can use React 16.4. It will be completely removed in React 17. If you enable

StrictMode or AsyncMode, you can use it in this way, but you will receive a warning:

  • UNSAFE_componentWillMount

  • UNSAFE_componentWillReceiveProps

  • UNSAFE_componentWillUpdate

static getDerivedStateFromProps

When

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.

What is a static method? A static method is a method that exists within the class, not within an instance of the class. Static methods cannot access

this, and they are modified with the static keyword in front when they are declared.

But, here comes the problem. Since this method has no way to access

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
  }
}
Copy after login
The effect of calling this method is the same as calling

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.

Things worth noting

You need to define the value of the initial state. Whether it's in

constructor, or a class attribute. Otherwise, a warning will be reported.

This method

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

getDerivedStateFromProps

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

componentDidUpdate

. If you don’t like to use the

static

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) =&gt; {   // Your code here }</pre><div class="contentsignin">Copy after login</div></div> <h2>Static Mode</h2> <p>严格模式是一个新的方式来确保你的代码是按照最佳实践开发的。它实际是一个在<code>React.StrictMode下的组件。它可以用在你的组件树的任何一部分上。

import {StrictMode} from 'react'

class Application extends React.Component {
  render() {
    return (
      <StrictMode>
        <Context.Provider value={{background: &#39;black&#39;, color: &#39;white&#39;}}>
          <Header />
          <Main />
          <Footer />
        </Context.Provider>
      </StrictMode>
    );
  }
}
Copy after login

如果一个在StricMode子树里的组件使用了componentWillMount方法,那么你会看到一个报错消息。

AsyncMode

异步模式在React.unsafe_AsyncMode下。使用AsncMode也会打开StrictMode模式下的警告。

相关推荐:

React 16.3之Context API详解


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template