以下記錄目前萌新我對React-Context的認知,若有錯誤請大大們指教
React-Context類似於Redux的概念,同樣具有以下物件:
1.
global state: 作為每一個component隨時都可以取得的state。
2.
action: 內容包含欲對global state做的動作(action.type)與當下欲傳入global state的資料(action.payload)。
3.
dispatch: 接收action,透過將action傳入reducer更新state。
4.
reducer: 接收引數action與state,透過傳入引數action.type判斷欲對state改變的動作,並回傳新的state。
使用React-Context會用到以下物件做更簡易的控制:
1.
createContext(): 宣告一個使用React-Context的component。
2.
<React-Context.Provider>: React-Context的一個component,該component的
value prop即為global state資料。
3.
useReducer(): 傳入要使用的reducer和初始state引數,並回傳當前state和dispatch()
4.
useContext(): 回傳
value prop資料當前狀態。
簡易範例(省略import):
/* StateProvider.js */
透過createContext()產生StateContext component,
利用箭頭函式實字宣告函數useStateValue(簡易custom Hook),該函數執行useContext(..)獲得value prop資料。
為了簡潔,創建StateProvider component,接收reducer, state初始值, StateProvider在JSX包裹的子物件,並回傳React內建的StateContext與子物件
*為了達到redux的管理方式,此刻global state並非直接傳入value prop,而是傳入useReducer
/*
index.js */
將設定好的初始值與reducer傳入StateProvider
當要使用或改變global state時,只需import useStateValue,執行後並解構接收回傳的global state與欲改變global state的dispatch函式,即可在任何一個component操作!