Custom Hooks 中使用 React Context
在上一篇 對(duì)于 Custom React Hooks 一些思考 文章末尾提及了 React Context,那么在本篇中我們將了解一下 React Context 怎么解決狀態(tài)共享問題以及一些其它想法。

關(guān)于 React Context
提供 官網(wǎng)對(duì)于 ?usecontext 的介紹
const?value?=?useContext(MyContext);
無論組件在組件樹中的深度如何,React Context 都為組件提供數(shù)據(jù)。上下文用于管理全局?jǐn)?shù)據(jù),例如 全局狀態(tài)、主題、服務(wù)、用戶設(shè)置等。
那么我們回到上篇文章提及到的例子吧,如何在父子組件中共享 useBoolean 返回的狀態(tài)呢?

怎樣使用 Context
在給出一份解決方案前,先來說明一下如何使用 Context。步驟也是比較簡(jiǎn)單:
creating the context providing the context consuming the context
creating the context
首先在 src 目錄下創(chuàng)建一個(gè)名為 context 的文件夾,創(chuàng)建 index.tsx 文件
通過 createContext ?來進(jìn)行創(chuàng)建操作
import?{?createContext?}?from?'react';
const?GlobalContext?=?createContext({})
export?default?GlobalContext;
providing the context
接下來,在父組件中 providing the context,并且將之前編寫的 Custom Hooks(useBoolean)返回的 state 作為 value 值提供給子組件。
import?SubApp?from?'./subApp';
import?useBoolean?from?'./custom-hooks/useBoolean/index';
import?GlobalContext?from?'./context/index'
function?App()?{
??const?[state,?{?toggle,?setTrue,?setFalse?}]?=?useBoolean(true);
??return?(
????
??????Effects:{JSON.stringify(state)}</p>
??????
????????
button>
????????
瀏覽
47評(píng)論
圖片
表情
