首頁  >  問答  >  主體

為什麼每個 React 元件都需要使用 useDispatch?

是的,這個問題似乎與這個問題重複:

每個元件應該有一個 useDispatch 嗎?

但它並不重複。我提供不同的方法:

假設我有 3 個子元件,它們都使用 Redux Toolkit 的調度函數。

通常的方式是這樣的:

const ChildA = () => {
  const dispatch = useAppDispatch();

  const incr = useCallback(() => {
    dispatch(increment());
  }, [dispatch]);

  return <button onClick={incr}>ChildA</button>;
};

const ChildB = () => {
  const dispatch = useAppDispatch();

  const incr = useCallback(() => {
    dispatch(increment());
  }, [dispatch]);

  return <button onClick={incr}>ChildB</button>;
};

const ChildC = () => {
  const dispatch = useAppDispatch();

  const incr = useCallback(() => {
    dispatch(increment());
  }, [dispatch]);

  return <button onClick={incr}>ChildC</button>;
};

export const MyApp = () => {
  const dispatch = useAppDispatch();

  const count = useAppSelector((state) => state.counter.value);

  const incr = useCallback(() => {
    dispatch(increment());
  }, [dispatch]);

  return (
    <div>
      <button onClick={incr}>MyApp</button>

      <ChildA />
      <ChildB />
      <ChildC />

      <div>{count}</div>
    </div>
  );
};

但是如果我這樣做呢?請參閱:

export const glo: {
  dispatch: ReturnType<typeof useAppDispatch>;
} = {
  // @ts-ignore
  dispatch: null
};

const ChildA = () => {
  const incr = useCallback(() => {
    glo.dispatch(increment());
  }, []);

  return <button onClick={incr}>ChildA</button>;
};

const ChildB = () => {
  const incr = useCallback(() => {
    glo.dispatch(increment());
  }, []);

  return <button onClick={incr}>ChildB</button>;
};

const ChildC = () => {
  const incr = useCallback(() => {
    glo.dispatch(increment());
  }, []);

  return <button onClick={incr}>ChildC</button>;
};

export const MyApp = () => {
  const dispatch = useAppDispatch();
  glo.dispatch = dispatch;
  if (!glo.dispatch) {
    throw new Error("dispatch is falsy");
  }

  const count = useAppSelector((state) => state.counter.value);

  const incr = useCallback(() => {
    glo.dispatch(increment());
  }, []);

  return (
    <div>
      <button onClick={incr}>MyApp</button>

      <ChildA />
      <ChildB />
      <ChildC />

      <div>{count}</div>
    </div>
  );
};

經我測試,它也運作良好。請告訴我,為什麼我應該按照通常的方式做?現在新程式碼(基於 glo 的程式碼)更大,但那是因為我們只有 3 個子元件。當我們有 30 多個子元件時,基於 glo 的程式碼將會小得多,也更容易理解。

這裡是差異:

https://i.ibb.co/tKWv2Qc/image.png

這是 CodeSandbox 連結:

https://codesandbox.io/s/clever-monad-c99q3k?file=/src/features/index.tsx

##
P粉291886842P粉291886842175 天前394

全部回覆(1)我來回復

  • P粉845862826

    P粉8458628262024-03-29 12:59:55

    例如,該調度函數將在您的測試中發生變化。

    如果沒有測試,在某些環境中這樣做本身並不是“錯誤”,但也不是一個大勝利。
    如果你的應用程式中有一行const dispatch = useAppDispatch(); ,那麼很有可能,當js 套件被gzip 傳輸時(現在這很正常),它會gzip 到3 或4無論如何位元組.

    如果您確實想刪除此處的程式碼,請刪除 useCallback ,因為將回呼直接傳遞到 html 時完全沒有必要。

    回覆
    0
  • 取消回覆