Reactの小さなカスタムフック(ジェネレーター、sagas、rxjs)に関する壮大な物語

パート2。ジェネレーター





プレリュード

タスクは、リアクタンスのカウントダウンを備えたプリローダーを実装することでした。なぜなら グーグルの方法がわからず、自転車を彫刻するのが大好きです(2人乗りの良い2人乗りは、2台の自転車「ウクライナ」からのものであることが判明しました)。その後、非同期の分野を深く掘り下げる運命にありました。先に進んで、ジェネレーター、redux-saga、rxjsを使用してこのプリローダーを実装したと言います。それは非常に興味深い経験であり、手続きの過程で、明白なことを説明する記事とスタックオーバーフローに関する純粋に特定の情報の断片を除いて、私はそれを見つけられなかったことを考えると、それを共有したいと思います。





つまり、パート1-カスタムフックを作成します。





プリローダー構造

読み込みインジケーターのスケールとして、サイト上の写真の数を選択しました(他のリソースも選択できます)。私の場合、これらはページ上で最も重いリソースでした。





なぜなら これはreactで行う必要があり、もちろんカスタムフックの形で設計し、usePreloaderという名前を付けました。





プリローダーコード自体
import React from "react";

export default function Preloader() {
  return (
    <div className="preloader__wrapper">
      <div className="preloader">
        <svg
          width="300"
          height="300"
          viewBox="0 0 300 300"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M300 150C300 232.843 232.843 300 150 300C67.1573 300 0 232.843 0 150C0 67.1573 67.1573 0 150 0C232.843 0 300 67.1573 300 150ZM20.7679 150C20.7679 221.373 78.6271 279.232 150 279.232C221.373 279.232 279.232 221.373 279.232 150C279.232 78.6271 221.373 20.7679 150 20.7679C78.6271 20.7679 20.7679 78.6271 20.7679 150Z"
            fill="#F3F3F3"
          />
          <path
            d="M289.616 150C295.351 150 300.037 154.655 299.641 160.376C297.837 186.392 289.275 211.553 274.72 233.336C258.238 258.003 234.811 277.229 207.403 288.582C179.994 299.935 149.834 302.906 120.736 297.118C91.6393 291.33 64.9119 277.044 43.934 256.066C22.9561 235.088 8.66999 208.361 2.88221 179.264C-2.90558 150.166 0.0649254 120.006 11.4181 92.5975C22.7712 65.1886 41.9971 41.7618 66.6645 25.2796C88.4468 10.725 113.608 2.16293 139.624 0.359232C145.345 -0.0374269 150 4.64906 150 10.384C150 16.1189 145.343 20.7246 139.627 21.1849C117.723 22.9486 96.5686 30.2756 78.2025 42.5475C56.9504 56.7477 40.3864 76.931 30.6052 100.545C20.8239 124.159 18.2647 150.143 23.2511 175.212C28.2375 200.28 40.5457 223.307 58.6191 241.381C76.6926 259.454 99.7195 271.762 124.788 276.749C149.857 281.735 175.841 279.176 199.455 269.395C223.069 259.614 243.252 243.05 257.453 221.797C269.724 203.431 277.051 182.277 278.815 160.373C279.275 154.657 283.881 150 289.616 150Z"
            fill="#6CAE30"
          />
        </svg>
      </div>
      <div className="preloader__counter">0%</div>
    </div>
  );
}

      
      







プリローダースタイル
.App {
  font-family: sans-serif;
  text-align: center;
}

.preloader__wrapper {
  position: fixed;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  z-index: 2000;
}

.preloader {
  position: relative;
  width: 18.75rem;
  height: 18.75rem;
}
.preloader svg {
  width: 18.75rem;
  height: 18.75rem;
  -webkit-animation: spin 4s infinite linear;
  animation: spin 4s infinite linear;
}
.preloader__counter {
  margin-top: 1.625rem;
  padding-left: 1rem;
  font-family: sans-serif;
  font-size: 3.125rem;
  line-height: 1;
  color: #6cae30;
}

@media (max-width: 900px) {
  .preloader {
    width: 6.25rem;
    height: 6.25rem;
  }
  .preloader svg {
    width: 6.25rem;
    height: 6.25rem;
  }
  .preloader__counter {
    margin-top: 0.75rem;
    padding-left: 0.5rem;
    font-size: 2.125rem;
  }
}

@-moz-keyframes spin {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

      
      







フックの実装

フックロジックは、ページ上のすべての<img>タグを検索し、ロードイベントとエラーイベントのハンドラーをアタッチすることです。これは、次のコードを使用して行われます





const updateCounter = () => {
  dispatch({
    type: ACTIONS.SET_COUNTER,
    data: state.counter + state.counterStep
  });
};

const checkImageLoading = (url) => {
  const imageChecker = new Image();
  imageChecker.addEventListener("load", updateCounter);
  imageChecker.addEventListener("error", updateCounter);
  imageChecker.src = url;
};
      
      



フックには状態があり、インジケーターのステップと現在のインジケーターの状態が保存されます。この(最初の)部分では、プリローダーはリアクションフックのみを使用して実装されますが、いくつかのバージョンがあります。状態を保存するためにreduxを接続しません。これはカスタムフックであり、将来的に再利用したいと考えています。





Jsソースコード
export const SET_COUNTER = "SET_COUNTER";
export const SET_COUNTER_STEP = "SET_COUNTER_STEP";
export const initialState = {
  counter: 0,
  counterStep: 0,
};
export const reducer = (state, action) => {
  switch (action.type) {
    case SET_COUNTER:
      return { ...state, counter: action.data };
    case SET_COUNTER_STEP:
      return { ...state, counterStep: action.data };
    default:
      throw new Error("This action is not applicable to this component.");
  }
};

export const ACTIONS = {
  SET_COUNTER,
  SET_COUNTER_STEP,
};

      
      







オプション1(わかりやすくするために機能していません)。useReducer

, , useRef . checkImageLoading state .





usePreloader.js
import { useReducer, useEffect } from "react";
import { reducer, initialState, ACTIONS } from "./state";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    dispatch({
      type: ACTIONS.SET_COUNTER,
      data: state.counter + state.counterStep
    });
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      dispatch({
        type: ACTIONS.SET_COUNTER_STEP,
        data: Math.floor(100 / imgArray.length) + 1
      });
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useEffect(() => {
    if (counterEl) {
      state.counter < 100
        ? (counterEl.innerHTML = `${state.counter}%`)
        : hidePreloader(preloaderEl);
    }
  }, [state]);

  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;
      
      







2. useReducer + useRef

, useRef . state .





:





//   state
const stateRef = useRef(state);
      
      



state current stateRef:





const updateCounter = () => {
  dispatch({
    type: ACTIONS.SET_COUNTER,
    data: stateRef.current.counter + stateRef.current.counterStep //    state,   stateRef
  });
};
      
      



state





stateRef.current.counter < 100
	? (counterEl.innerHTML = `${stateRef.current.counter}%`) //    state,   stateRef
	: hidePreloader(preloaderEl);
      
      



state, :





useEffect(() => {
  stateRef.current = state; //   state,     state
  ...
}, [state]);
      
      



useReducer + useRef
import { useReducer, useEffect, useRef } from "react";
import { reducer, initialState, ACTIONS } from "./state";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  //   state
  const stateRef = useRef(state);

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    dispatch({
      type: ACTIONS.SET_COUNTER,
      data: stateRef.current.counter + stateRef.current.counterStep //    state,   stateRef
    });
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      dispatch({
        type: ACTIONS.SET_COUNTER_STEP,
        data: Math.floor(100 / imgArray.length) + 1
      });
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useEffect(() => {
    stateRef.current = state; //   state,     state
    if (counterEl) {
      stateRef.current.counter < 100
        ? (counterEl.innerHTML = `${stateRef.current.counter}%`) //    state,   stateRef
        : hidePreloader(preloaderEl);
    }
  }, [state]);

  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;

      
      







. ( network devtools), . , . ..





useEffect(() => {
  ...
}, [state]);
      
      



state. stateRef.current . .





, useEffect useLayoutEffect:





  useLayoutEffect(() => {
    stateRef.current = state;
    if (counterEl) {
      stateRef.current.counter < 100
        ? (counterEl.innerHTML = `${stateRef.current.counter}%`)
        : hidePreloader(preloaderEl);
    }
  }, [state]);
      
      



.





useEffect - . .. - state .





useLayoutEffect - . .. .





: , , useLayoutEffect; , - useEffect.





3. useState + useRef

useReducer, .. : . useState. couterStep :





  const [counterStep, setCounterStep] = useState(0);
  const counterStepStateRef = useRef(counterStep);
  const setCounterStepState = (data) => {
    counterStepStateRef.current = data;
    setCounterStep(data);
  };
      
      



useState + useRef
import { useEffect, useLayoutEffect, useRef, useState } from "react";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [counter, setCounter] = useState(0);
  const counterStateRef = useRef(counter);
  const setCounterState = (data) => {
    counterStateRef.current = data;
    setCounter(data);
  };

  const [counterStep, setCounterStep] = useState(0);
  const counterStepStateRef = useRef(counterStep);
  const setCounterStepState = (data) => {
    counterStepStateRef.current = data;
    setCounterStep(data);
  };

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    setCounterState(counterStateRef.current + counterStepStateRef.current);
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      setCounterStepState(Math.floor(100 / imgArray.length) + 1);
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useLayoutEffect(() => {
    if (counterEl) {
      counterStateRef.current < 100
        ? (counterEl.innerHTML = `${counterStateRef.current}%`)
        : hidePreloader(preloaderEl);
    }
  }, [counter, counterStep]);
  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;

      
      











export default function App() {
  usePreloader();
  return (
    <div className="App">
      <Preloader />
      ...
    </div>
  );
}
      
      







:

:









  • useReducer useState





  • useRef





  • useEffectフックとuseLayoutEffectフックを使用した場合のコンポーネントの動作の違い









サンドボックスリンク





リポジトリリンク





これで終わりかもしれません。フックは機能します。しかし、このプリローダーは、予期せず、イベントのフローとその非同期処理を処理するための優れた例であることが判明しました。したがって、楽しみは次の部分から始まります。





ジェネレーターから始めましょう、あるいは続けましょう...
















All Articles