差異處
這裏顯示兩個版本的差異處。
web:reactjs:react_hook:usecontext [2019/02/24 23:53] tony [createContext] |
web:reactjs:react_hook:usecontext [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | ====== React Hook - useContext ====== | ||
- | ===== Introduction ===== | ||
- | 我在Study React所撰寫的第一個範例是系統的登入與登出,而登入狀態需要由上層元件傳遞給登入與登出元件做修改。在這範例中,由於上層元件與登入元件只有一層,所以我可以透過建構元將狀態傳遞過去;然而登出元件與上層元件相差太多層,傳遞並不是那麼容易。\\ | ||
- | \\ | ||
- | 在React Hook推出之前,有flux、Redux,或者是後來推出的Context,都可以解決這個問題;而本篇要介紹的useContext,我認為比前面幾個都還容易達到需求。 | ||
- | ===== createContext ===== | ||
- | export const AuthContext = React.createContext(null); | ||
- | |||
- | function App(){ | ||
- | const [ state, setState ] = useState(false); | ||
- | |||
- | let route_target; | ||
- | if( !state ) { | ||
- | route_target = <Route path="/" name="Login" component={LoginForm}/>; | ||
- | } else | ||
- | route_target = <Route path="/" name="Home" component={DefaultLayout} />; | ||
- | |||
- | return ( | ||
- | <AuthContext.Provider value={[state, setState]}> | ||
- | <HashRouter> | ||
- | <Switch> | ||
- | {route_target} | ||
- | </Switch> | ||
- | </HashRouter> | ||
- | </AuthContext.Provider> | ||
- | ); | ||
- | } | ||
- | |||
- | ===== useContext ===== | ||
- | |||
- | ===== Reference ===== | ||
- | * [[https://tinkerylabs.com/react-context-api-with-hooks/|React Context API + State Hook]] | ||