React 16バージョンの新機能について(メモ)

40652 ワード

簡単なメモ

  • react 16.0.0
  • 1.配列と文字列renderをサポートします.
  • 2.Error boundary(エラー境界)
  • 3.Fiberコアアルゴリズムの実装
  • react 16.1.0
  • 1.callReturn
  • react 16.2.0
  • 1.Fragment
  • react 16.3.0
  • 1.context API
  • 2.ライフサイクルの更新
  • 3.createRef/forwordRef;
  • 4.StrictMode
  • react 16.4.0
  • 1.Pointer Events API
  • react 16.5.0
  • React Profiler
  • react 16.6.0
  • 1.Memo:
  • 2.lazy、suspense
  • 3.static getDerivedStateFromError
  • 4、static contextType
  • react 16.7.0
  • Hooks

  • react 16.0.0


    1.配列と文字列renderをサポートする。


    React elements、配列、Fragments、Portal、String/numbers、boolean/nullの5つのクラスを返すことをサポートします.
    class Example extends React.Component {
      render() {
        return [
          <div key="1">first element</div>,
          <div key="2">second element</div>,
        ];
      }
    }
    

    2.Error boundary(エラー境界)

    //       ErrorBoundary
    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { error: null, errorInfo: null };
      }
      
      componentDidCatch(error, errorInfo) {
        // Catch errors in any components below and re-render with error message
        this.setState({
          error: error,
          errorInfo: errorInfo
        })
        // You can also log error messages to an error reporting service here
      }
      
      render() {
        //           
        if (this.state.errorInfo) {
          // Error path
          return (
            <div>
              <h2>Something went wrong.</h2>
              <details style={{ whiteSpace: 'pre-wrap' }}>
                {this.state.error && this.state.error.toString()}
                <br />
                {this.state.errorInfo.componentStack}
              </details>
            </div>
          );
        }
        //     ,      
        return this.props.children;
      }  
    }
    
    class BuggyCounter extends React.Component {
      constructor(props) {
        super(props);
        this.state = { counter: 0 };
        this.handleClick = this.handleClick.bind(this);
      }
      
      componentWillMount() {
        throw new Error('I am crash');
      }
      
      handleClick() {
        this.setState(({counter}) => ({
          counter: counter + 1
        }));
      }
      
      render() {
        if (this.state.counter === 5) {
          // Simulate a JS error
          throw new Error('I crashed!');
        }
        return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
      }
    }
    
    function App() {
      return (
        <div>
          <p>
            <b>
              This is an example of error boundaries in React 16.
              <br /><br />
              Click on the numbers to increase the counters.
              <br />
              The counter is programmed to throw when it reaches 5. This simulates a JavaScript error in a component.
            </b>
          </p>
          <hr />
            <ErrorBoundary>
            <p>These two counters are inside the same error boundary. If one crashes, the error boundary will replace both of them.</p>
            <BuggyCounter />
            </ErrorBoundary>
          <hr />
    
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
    

    3.Fiberコアアルゴリズムの実現


    16バージョンのコアであり、最適化されたreact性能を向上させる.

    react 16.1.0


    1.callReturn


    (react-call-return npm)プラグイン学習と応用

    react 16.2.0


    1.Fragment


    コンポーネントの役割は、Domtreeに一部のサブ要素を追加し、これらの要素に追加の親ノードを提供する必要がないことです.例:
    render() {
      return (
        <Fragment>
          Some text.
          <h2>A heading</h2>
          More text.
          <h2>Another heading</h2>
          Even more text.
        </Fragment>
      );
    }
    

    Fragment公式使用チュートリアル

    react 16.3.0


    1.context API


    グローバル変数は、前のように伝える必要はありません.
    const ThemeContext = React.createContext('light');
    
    class App extends React.Component {
      render() {
     return (
          <ThemeContext.Provider value="dark">
            <Toolbar />
          </ThemeContext.Provider>
        );
      }
    }
    
    class Toolbar extends React.Component {
      static contextType = ThemeContext;
      render() {
       return <Button theme={this.context} />;
      }
    }
    

    2.ライフサイクルの更新変動

    //          
    add:getDerivedstatefromprops;
    	getsnapshotBeforeUpdate;
    	componentDidCatch;
    //            
    unsafe:componentwillMount
           componentwillUpdate
           componentwillReceiveProps
    

    3.createRef/forwordRef;


    16より前:
    <input type="text" ref={element => this.textInput = element} />
    

    16以降
    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();
      }
    }
    

    4.StrictMode


    開発段階で厳格なモデルを開き、応用の潜在的な問題を発見し、応用の頑丈性を高めることができる.1安全でないライフサイクルを使用するコンポーネントを識別する2 string refを使用したアラート3 findDOMNodeを使用したアラート4いくつかの副作用を検出する方法5廃棄context APIの使用を警告する
    function ExampleApplication() {
     return (
        <div>
          <Header />
          <React.StrictMode>
            <div>
              <ComponentOne />
              <ComponentTwo />
            </div>
          </React.StrictMode>
          <Footer />
        </div>
      );
    }
    

    react 16.4.0


    1.Pointer Events API


    Hmtl 5のイベント仕様の1つで、マウス(Mouse)、タッチ(touch)、タッチペン(pen)の3つのイベントを統合したAPI onPointerDown onPointerMove onPointerEnter onPointerLeave onPointerOveronPointerOu

    react 16.5.0


    React Profiler


    Googleプラグインをダウンロードすれば、コンポーネントのレンダリングに時間がかかることを検出できます.

    react 16.6.0


    1.Memo:

    import React, { memo } from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    function Demo(props) {
      console.log("render");
      return <div>{props.name}</div>;
    }
    
    const Demo1 = memo(function Demo(props) {
      console.log("render");
      return <div>{props.name}</div>;
    });
    
    class App extends React.Component {
      state = { count: 0 };
      handleClick = () => {
        this.setState({ count: 1 });
      };
      render() {
        return (
          <div className="App">
            <h1>Hello Memo</h1>
            <button onClick={this.handleClick}>
              This is Memo Demo{this.state.count}
            </button>
            <Demo1 name={"daisy"} />
          </div>
        );
      }
    }
    

    関数の前にMemoを追加すると、PureComponentのようにshouldComponentUpdateでレンダリング機能を最適化できます.

    2.lazy、suspense


    動的ロードコンポーネントの実装
    <!--import B from "./B";-->
    
    //             ,         
    const B = lazy(() => import("./B"));
    
     <Suspense fallback={<div>Loading...</div>}>
        <TabPanel>
        <B />
        </TabPanel>
     </Suspense>
    

    3.static getDerivedStateFromError


    ライフサイクルトリガ条件は、コンポーネントの放出エラーです.
    class ErrorBoundary extends React.Component {
      state = { hasError: false };
      
      static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        //   state    render      fallback UI
        return { hasError: true };
      }
      
      componentDidCatch(error, info) {
        // You can also log the error to an error reporting service
        logErrorToMyService(error, info);
      }
      
      render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>Something went wrong.</h1>;
        }
        
        return this.props.children; 
      }
    

    4、static contextType


    小包は要らないcontextでいいです.このドキュメントは皆さんがよく調べる必要があります.新版contextの使い方です.reduxのconnect原理はそれに基づいて生まれています.

    react 16.7.0


    Hooks


    1.Hookが解決しなければならないのは状態論理多重問題であり、jsxネスト地獄は発生しない.2.Hooksは、関数コンポーネントでのみ使用できます.たとえば、次のようになります.
    import React, { useState } from 'react';
        
        function Example() {
          // count       ;setCount    ,useState(0)     0
          const [count, setCount] = useState(0);
          const [ok, setOk] = useState("yes");
    
          return (
            <div>
              <p>You clicked {count} times</p>
              <button onClick={() => setCount(count + 1)}>
                Click me
              </button>
            </div>
          );
        }