Rumah  >  Artikel  >  hujung hadapan web  >  Contoh API Konteks Reaksi Mudah Ditaip Sepenuhnya

Contoh API Konteks Reaksi Mudah Ditaip Sepenuhnya

Linda Hamilton
Linda Hamiltonasal
2024-10-28 07:10:30904semak imbas

Fully Typed, Easy React Context API Example

Helah untuk tidak perlu menjaga jenis konteks adalah mudah!

Jika anda menggunakan API konteks, maka satu masalah ialah penjagaan anak mengikut jenisnya.

Satu lagi perlu menggunakan berbilang import untuk menggunakannya apabila anda memerlukannya.

Dengan contoh ini, kami menyelesaikan kedua-dua masalah dan menjadikannya pantas dan mudah untuk menggunakan API Konteks React.

Contoh Salin Tampal

Salin, tampal, kemudian cuma gantikan semua “contoh” kepada apa yang perlu anda namakan dan anda sudah bersedia untuk pergi.

(Selepas itu, akan ada versi ulasan penuh.)

import {
  createContext,
  useCallback,
  useContext,
  useDeferredValue,
  useMemo,
  useState,
} from 'react';

function useContextValue(init: number = 0) {
  const [state, setState] = useState(init);

  const doubleValue = state * 2;
  const defferedStringValue = useDeferredValue(state.toString());

  const reset = useCallback(() => {
    setState(init);
  }, []);

  const value = useMemo(
    () => ({
      state,
      doubleValue,
      defferedStringValue,
      reset,
    }),
    [
      state,
      doubleValue,
      defferedStringValue,
      reset,
    ],
  );

  return value;
}

type ExampleContext = ReturnType<typeof useContextValue>;

const Context = createContext<ExampleContext>(null!);

Context.displayName = 'ExampleContext';

export function ExampleContextProvider({
  children,
  initValue = 0,
}: {
  children: React.ReactNode;
  initValue?: number;
}) {
  const value = useContextValue(initValue);
  return <Context.Provider value={value}>{children}</Context.Provider>;
}

export function useExample() {
  const value = useContext(Context);

  if (!value) {
    throw new Error('useExample must be used within a ExampleContextProvider');
  }

  return value;
}

Versi Komen

import {
  createContext,
  useCallback,
  useContext,
  useDeferredValue,
  useMemo,
  useState,
} from 'react';

/**
 * We create a custom hook that will have everything
 * that would usually be in the context main function
 *
 * this way, we can use the value it returns to infer the
 * type of the context
 */
function useContextValue(init: number = 0) {
  // do whatever you want inside

  const [state, setState] = useState(init);

  const doubleValue = state * 2;
  const defferedStringValue = useDeferredValue(state.toString());

  // remember to memoize functions
  const reset = useCallback(() => {
    setState(init);
  }, []);

  // and also memoize the final value
  const value = useMemo(
    () => ({
      state,
      doubleValue,
      defferedStringValue,
      reset,
    }),
    [
      state,
      doubleValue,
      defferedStringValue,
      reset,
    ],
  );

  return value;
}

/**
 * Since we can infer from the hook,
 * no need to create the context type by hand
 */
type ExampleContext = ReturnType<typeof useContextValue>;

const Context = createContext<ExampleContext>(null!);

Context.displayName = 'ExampleContext';

export function ExampleContextProvider({
  children,
  /**
   * this is optional, but it's always a good to remember
   * that the context is still a react component
   * and can receive values other than just the children
   */
  initValue = 0,
}: {
  children: React.ReactNode;
  initValue?: number;
}) {
  const value = useContextValue(initValue);
  return <Context.Provider value={value}>{children}</Context.Provider>;
}

/**
 * We also export a hook that will use the context
 *
 * this way, we can use it in other components
 * by importing just this one hook
 */
export function useExample() {
  const value = useContext(Context);

  /**
   * this will throw an error if the context
   * is not used within the provider
   *
   * this also avoid the context being "undefined"
   */
  if (!value) {
    throw new Error('useExample must be used within a ExampleProvider');
  }

  return value;
}

Kata Akhir

Itu sahaja. API Konteks adalah lebih mudah dan lebih halus daripada yang sepatutnya, tetapi ia merupakan alat yang berkuasa untuk kes-kes di mana ia perlu digunakan.

Hanya ingat bahawa API Konteks React bukanlah Redux (atau pengurus negeri lain) dan anda tidak sepatutnya memasukkan keseluruhan keadaan aplikasi ke dalamnya.

Nah, anda boleh, tetapi ia boleh menyebabkan masalah yang tidak perlu.

Ini ditulis dengan React < 19 dalam fikiran, dengan pengkompil baharu datang, hafalan dan rendering yang tidak perlu mungkin tidak menimbulkan masalah.

Atas ialah kandungan terperinci Contoh API Konteks Reaksi Mudah Ditaip Sepenuhnya. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn