反応フックの使用


何が反応フックですか?


フックは16.8に反応するために加えられました、そして、彼らは我々が州を使用するのを許します、そして
クラスを書くことなく他のライフサイクルメソッド.
彼らは機能的なコンポーネントだけを使用することを可能にします.
あなたは、彼らが機能性へのちょうど置き換えであるならば、なぜ第1の場所でフックを使うべきですか
私たちはすでにクラスのコンポーネントを使用している間!しかし、それはそうではありません、フックは多くの
クラスコンポーネントで使用されるライフサイクルメソッドの改善.
私たちは前のパターンよりもはるかにエレガントな方法でクロスカットの懸念に対処するためにフックを反応させる
例えばhigher-order components
and render props .
ロギングと認証のような機能性はコンポーネント特有でありません、そして、反応フックは我々にこの種の再利用できるふるまいを構成要素に付けるのを許します.
このブログ記事では、2つの最も重要なフックを使用する方法を示します
あなたはあなたのクラスレス反応アプリを構築する必要があります、私はランダムな冗談ジェネレータを構築することによってデモを使用して
このパブリックAPI
api: https://v2.jokeapi.dev/joke/Any

米国不動産


このメソッドは、機能コンポーネントの状態を使用できます.
この状態を変更する状態とメソッドを配列で返します.
const [state,setState] = useState(); 
// state will have the initial state in this case undefined
// setState is the function that we can use to update the state
状態を更新する
setState("words") 
// you would use it as such, 
//the parameter takes in the value you want to update the state with
我々のアプリでは、我々が作成する基本的なセットアップを使用します
そして次のように更新します
import {useState} from 'react';
import './App.css';

function App() {
    //we created a state joke that is intialized with a string value for now
    const [joke,setJoke] = useState("There are only 10 kinds of people in this world: those who know binary and those who don't.")

    return (
        <div className="App">
        <header className="App-header">
            <h3>{joke}</h3>
        </header>
        </div>
    );
}

export default App;

今我々のアプリはこのように見える!🤘


(それはおかしい冗談だと言わざるを得ない)

効果


反応フックは、以下を紹介しますuseEffect() 置換方法
クラスコンポーネントのライフサイクルメソッドcomponentDidMount , componentDidUpdate , and componentWillUnmount .
また、あなたの機能部品の副作用を許します.
ドキュメントオブジェクトモデルの内容を変更したり、データを取得するなど.useEffect() すべてのコンポーネントのレンダリング後に実行されます.
反応ドキュメンテーションから

useEffect Accepts a function that contains imperative, possibly effectful code.

Mutations, subscriptions, timers, logging, and other side effects are not allowed
inside the main body of a function component (referred to as React’s render phase).
Doing so will lead to confusing bugs and inconsistencies in the UI.

Instead, use useEffect. The function passed to useEffect will run after the render
is committed to the screen. Think of effects as an escape hatch from React’s purely
functional world into the imperative world.

By default, effects run after every completed render,
but you can choose to fire them only when certain values have changed.


それは取るにはたくさんです!
どのような効果的なコードを説明することから始めましょうか?
有効なコードは関数の範囲外の何かに影響するコードです
それは、副作用としても知られてexcutedされている
このようなイベントで副作用が観察できます.
  • グローバル変数の変更
  • 変数への代入などのローカルスコープの変更
  • オブジェクトのプロパティへの割り当てや配列へのプッシュなどの場所のメモリの変更
  • ネットワークリクエストの作成
  • 端末への印刷
  • DOMツリーの変更
  • //Example
    useEffect(()=>{
        fetchData() // making a network request
        //eveythig inside this function will be called on every render
        //fetchData() will be called everytime the component re-renders
    })
    
    useEffect 依存配列を2番目のパラメータとして受け取ります.
    これは、我々がそれを望むときだけ、それを実行させるのを許します.
    私たちのジョークアプリでは、すべてのレンダリングの状態を更新するには、ランダムジョークAPIを使用します.
    それをするために我々はuseEffect() メソッドとsetJoke() 我々が得た方法useState()
    import {useState, useEffect} from 'react';
    import './App.css';
    
    function App() {
    
        const [joke,setJoke] = useState("")
    
        useEffect(()=>{
            getRandomJoke();
        })
    
        //fetching the data and setting and updating state
        const getRandomJoke = async () => {
            const response = await fetch("https://v2.jokeapi.dev/joke/Any?type=single");
            const result = await response.json();
            if(!result.error){
                setJoke(result.joke);
            }
        }
    
        return (
            <div className="App">
            <header className="App-header">
                <h3>{joke}</h3>
            </header>
            </div>
        );
    }
    
    export default App;
    

    面白い冗談だよ!しかし、それは停止しません!
    The useEffect() メソッドは毎回実行中ですjoke 状態が変化し、これが実行されます
    無限ループで!
    依存関係の配列を使用するように修正するには、最初のレンダリングだけで実行してください
    それで、我々はそのような空の配列を通過します
    useEffect(()=>{
        getRandomJoke();
    },[]) //passed an empty array []
    
    (冗談)
    これは、最初のレンダリングだけで実行される今、それを修正!
    最後まで到達するための功績👍 !
    もっと多くの情報がカバーされますが、別の時間(別のブログ記事)のためにそれらを保つつもりです
    犯人をチェックするdocumentation
    あなたは、ランダムなジョークジェネレータのgithubレポを見つけることができますhere