/
TAG
React Context API

用 React Context API 實作跨組件傳值的功能

使用 React Context API 可以輕鬆實現跨組件傳值功能,適合不需要複雜狀態管理的小型應用。與 Vue 的 Vite + Pinia 類似,React 提供多種狀態管理選擇,如 Redux、Mobx、Zustand、Recoil 和 Jotai,其中 Context API 是內建的選項,無需額外安裝套件。本文介紹了如何在 React 中利用 Context API 來傳遞會員資料,通過建立 UserContext 並在 App 中使用 UserProvider 來共享資料,確保在不同組件間能夠輕鬆取得使用者資料。

實作過程包括在獨立的 context 檔案中打 API 取得即時會員資料,並使用 createContext 和 useContext 建立資料共享機制。在 App 組件中引入 UserProvider,然後在內部使用 useUser Hook 來讀取和渲染使用者資料。此外,其他頁面如 Home.jsx 也可以通過 useUser 獲取資料,實現簡單而有效的跨組件資料傳遞。這種方法適合需要跨組件傳遞資料但不需要複雜狀態管理的情況。...

Copyright © since 2008 MUKI space* / omegaSS theme All Rights Reserved.