React の useSessionStorage フック

ReactReactBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、React で useSessionStorage フックを使用して状態値を sessionStorage に永続化する方法を学びます。値を遅延初期化する方法、Storage.getItem()Storage.setItem() を使用して値を取得および保存する方法、および定義された関数を使用して状態変数を更新する方法を学びます。この実験が終了するとき、React アプリケーション内で sessionStorage を使用してデータを保存および取得する方法をより深く理解しているでしょう。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react(("React")) -.-> react/StateManagementGroup(["State Management"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/FundamentalsGroup -.-> react/event_handling("Handling Events") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") react/StateManagementGroup -.-> react/use_state_reducer("Using useState and useReducer") subgraph Lab Skills react/jsx -.-> lab-38408{{"React の useSessionStorage フック"}} react/event_handling -.-> lab-38408{{"React の useSessionStorage フック"}} react/hooks -.-> lab-38408{{"React の useSessionStorage フック"}} react/use_state_reducer -.-> lab-38408{{"React の useSessionStorage フック"}} end

React useSessionStorage フック

VM 内には既に index.htmlscript.js が用意されています。一般的には、script.jsstyle.css にのみコードを追加すればよいです。

sessionStorage に永続化される状態付きの値とそれを更新する関数を作成するには、次の手順に従います。

  1. useState() フックを使用して、その値を遅延初期化する関数を指定します。
  2. try...catch ブロックと Storage.getItem() を使用して、Window.sessionStorage から値を取得しようとします。値が見つからない場合は、Storage.setItem() を使用して defaultValue を保存し、初期状態として使用します。エラーが発生した場合は、defaultValue を初期状態として使用します。
  3. 渡された値で状態変数を更新する関数を定義し、Storage.setItem() を使用して保存します。

以下は、実装例です。

const useSessionStorage = (keyName, defaultValue) => {
  const [storedValue, setStoredValue] = React.useState(() => {
    try {
      const value = window.sessionStorage.getItem(keyName);

      if (value) {
        return JSON.parse(value);
      } else {
        window.sessionStorage.setItem(keyName, JSON.stringify(defaultValue));
        return defaultValue;
      }
    } catch (err) {
      return defaultValue;
    }
  });

  const setValue = (newValue) => {
    try {
      window.sessionStorage.setItem(keyName, JSON.stringify(newValue));
    } catch (err) {}
    setStoredValue(newValue);
  };

  return [storedValue, setValue];
};

このフックをアプリケーションで使用するには、次のようにします。

const MyApp = () => {
  const [name, setName] = useSessionStorage("name", "John");

  return <input value={name} onChange={(e) => setName(e.target.value)} />;
};

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

右下隅の「Go Live」をクリックして、ポート 8080 でウェブサービスを実行してください。その後、Web 8080 タブを更新してウェブページをプレビューできます。

まとめ

おめでとうございます!あなたは React useSessionStorage フックの実験を完了しました。あなたの技術を向上させるために、LabEx でさらに多くの実験を行って練習することができます。