在本文中,我們將了解如何擺脫應用程式中的 React.Context 並找到這樣做的動機。
如果您閱讀本文,您可能熟悉 React,並且可能已經有了 React.Context 的經驗,但如果沒有,請隨時閱讀它並與可能感興趣的人分享。
上下文會降低可讀性、糾纏和限制應用程式。
看看這個基本範例:
看起來不太容易理解和可靠,是嗎?
以下是使用情境時的一些潛在問題:
有趣的事實:眾所周知的「承諾地獄」看起來很相似 ?♂️
loadClients() .then((client) => { return populate(client) .then((clientPopulated) => { return commit(clientPopulated); }); });
改為創建掛鉤。
讓我們用自訂 useTheme 掛鉤取代上面範例中的 ThemeContext:
import { useAppEvents } from 'use-app-events'; const useTheme = () => { const [theme, setTheme] = useState('dark'); /** Set up communication between the instances of the hook. */ const { notifyEventListeners, listenForEvents } = useAppEvents(); listenForEvents('theme-update', (themeNext: string) => { setTheme(themeNext); }); const updateTheme = (themeNext: string) => { setTheme(themeNext); notifyEventListeners('theme-update', themeNext); }; return { theme, updateTheme, }; };
我們使用了一個名為 use-app-events 的 npm 套件來讓 useTheme 掛鉤的所有實例進行通訊以同步其主題狀態。它確保在應用程式中多次調用 useTheme 時主題值相同。
此外,得益於 use-app-events 包,即使在瀏覽器標籤之間主題也將同步。
此時,不再需要 ThemeContext,因為可以在應用程式中的任何位置使用 useTheme 掛鉤來獲取當前主題並更新它:
const App = () => { const { theme, updateTheme } = useTheme(); updateTheme('light'); // Output:Current theme: lightreturnCurrent theme: {theme}; }
此方法的優點是什麼:
React.Context 確實是一個強大的工具,但如果與 use-app-events 套件一起正確實現,鉤子提供了一種更受控制和更可靠的方式來管理應用程式的全域狀態。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3