差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
web:reactjs:react_hook:usecontext [2019/02/25 00:06] tony [Introduction] |
web:reactjs:react_hook:usecontext [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | {{tag>reactjs}} | ||
====== React Hook - useContext ====== | ====== React Hook - useContext ====== | ||
===== Introduction ===== | ===== Introduction ===== | ||
行 8: | 行 9: | ||
===== createContext ===== | ===== createContext ===== | ||
+ | 首先透過React.createContext建立共用的Context變數AuthContext。在App元件中,透過useState宣告了成員變數authState,並使用AuthContext.Provider將變數分享給下層元件。從程式碼可以得知,如果authState為true就會render DefaultLayout元件;反之則是LoginForm元件。 | ||
<code javascript> | <code javascript> | ||
export const AuthContext = React.createContext(null); | export const AuthContext = React.createContext(null); | ||
行 32: | 行 34: | ||
</code> | </code> | ||
===== useContext ===== | ===== useContext ===== | ||
+ | 在我的LoginForm元件中,可以透過useContext去拿到authState與setAuthState。當使用者輸入帳號密碼並點擊Login Button後,會觸發handleSubmit,接著它會透過Auth.signIn去執行登入動作。在這裡會根據登入成功與否,去透過setAuthState更新authState。 | ||
<code javascript> | <code javascript> | ||
function LoginForm(){ | function LoginForm(){ | ||
行 97: | 行 100: | ||
</code> | </code> | ||
===== Unit Test ===== | ===== Unit Test ===== | ||
+ | 在單元測試部分,為了要傳遞共享的Context資料給LoginForm,於是我做了一個中繼的LoginFormComp,使用方式類似App的做法。除此之外,我使用了React Hook的useEffect;當LoginForm修改了登入狀態,它就會觸發useEffect裡面的動作,在這我用來標記登入成功與否。可以直接參考測試"Login success",在輸入帳號密碼與點擊Login Button後,就可以驗證authState是否為true。假如要模擬登入失敗的情況,可以使用mockImplementation讓它拋出例外。 | ||
<code java> | <code java> | ||
import {render, fireEvent, cleanup} from 'react-testing-library'; | import {render, fireEvent, cleanup} from 'react-testing-library'; | ||
行 154: | 行 158: | ||
}); | }); | ||
</code> | </code> | ||
+ | ===== 其它 ===== | ||
+ | 本篇文章中,我的Context僅儲存一個boolean變數;假如你的資料較為複雜,是可以透過json去建置資料。除此之外,針對資料部分,也可以獨立做成Model元件。後續有機會會再分享關於較複雜資料與jest的使用細節。 | ||
+ | |||
+ | |||
===== Reference ===== | ===== Reference ===== | ||
* [[https://tinkerylabs.com/react-context-api-with-hooks/|React Context API + State Hook]] | * [[https://tinkerylabs.com/react-context-api-with-hooks/|React Context API + State Hook]] |