面试题答案
一键面试- 创建 Context:
- 首先在项目中创建一个新的文件,比如
UserContext.js
。 - 使用
createContext
方法来创建上下文对象。
import { createContext } from'react'; const UserContext = createContext(); export default UserContext;
- 首先在项目中创建一个新的文件,比如
- 创建 Context 提供器:
- 在自定义的 App 组件文件(通常是
pages/_app.js
)中,导入刚刚创建的UserContext
。 - 创建一个状态来管理用户登录状态,例如
isLoggedIn
。 - 使用
UserContext.Provider
包裹应用的其他部分,将isLoggedIn
作为value
传递。
import React, { useState } from'react'; import UserContext from '../path/to/UserContext'; import type { AppProps } from 'next/app'; function MyApp({ Component, pageProps }: AppProps) { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <UserContext.Provider value={{ isLoggedIn, setIsLoggedIn }}> <Component {...pageProps} /> </UserContext.Provider> ); } export default MyApp;
- 在自定义的 App 组件文件(通常是
- 消费 Context:
- 在需要使用用户登录状态的组件中,导入
UserContext
。 - 使用
useContext
钩子来获取上下文的值。
import React, { useContext } from'react'; import UserContext from '../path/to/UserContext'; const MyComponent = () => { const { isLoggedIn, setIsLoggedIn } = useContext(UserContext); return ( <div> {isLoggedIn? <p>已登录</p> : <p>未登录</p>} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn? '退出登录' : '登录'} </button> </div> ); }; export default MyComponent;
- 在需要使用用户登录状态的组件中,导入
主要步骤总结:
- 创建 Context 对象。
- 在自定义 App 组件中通过
Provider
提供状态和更新函数。 - 在需要的组件中通过
useContext
消费 Context 中的状态和更新函数。