发布时间:2023-04-10 12:30
应用场景: 每个组件都需要获取登录的用户
相关知识点: createContext, 自定义Hooks, useContext
官方文档: https://zh-hans.reactjs.org/docs/context.html
项目地址: https://gitee.com/cjperfect/react_context
List和Header组件都能获取到AppProvider提供的参数, 前提是要被AppProvider包裹
import React from "react";
import Header from "./components/header";
import List from "./components/list";
import AppProvider from "./context/auth-provider";
import "./App.css";
// import { useAuth } from "./context/user-context";
function App() {
// const context = useAuth();
// console.log(context);
return (
<div className="App">
<AppProvider>
<Header />
<List />
</AppProvider>
</div>
);
}
export default App;
import React, { ReactNode } from "react";
import { AuthProvider } from "./user-context";
const AppProvider = ({ children }: { children: ReactNode }) => {
return <AuthProvider>{children}</AuthProvider>;
};
export default AppProvider;
也就是创建context的, 和真正的AppProvider分开, 好维护
import React, { ReactNode, useContext } from "react";
const AuthContext = React.createContext<
| {
name: "chenjiang";
age: 24;
}
| undefined
>(undefined);
AuthContext.displayName = "AppContext";
export const AuthProvider = ({ children }: { children: ReactNode }) => {
// AppProvider.tsx文件中传递了children, 这里需要接收
return (
<AuthContext.Provider
value={{
name: "chenjiang",
age: 24,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("请在AppProvider包裹的组件中使用");
}
return context;
};
List和Header组件内部使用
import React from "react";
import { useAuth } from "../context/user-context";
const Header = () => {
const context = useAuth();
console.log("header", context);
return (
<header>
header section===
{"AppProvider传递过来的" + context.name}
</header>
);
};
export default Header;