上下文
一句话解释
上下文是 React feature for passing 数据通过组件树 不使用 manually passing Props at 每个 level.
用大白话说
上下文 provides 方式到 share 值 (主题, current 用户, locale, 设置) 跨越整个组件树 不使用 prop drilling. 你创建上下文使用 createContext(defaultValue), provide 值使用 <Context.Provider value={...}>, and consume 它使用 useContext(Context) or <Context.Consumer>.
The Provider determines the value; all descendant consumers read from the nearest Provider above them. When the Provider's value changes, all consumers re-render.
Context is best for low-frequency, app-wide data. For high-frequency updates, Context can cause performance issues because every consumer re-renders on change. In those cases, consider splitting Contexts or using a state management library.
示例
const UserContext = createContext(null);
function App() {
const [user, setUser] = useState({ name: "Alice" });
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <h1>{user.name}</h1>;
}App provides 用户通过上下文. Profile 读取它 不使用接收它 as prop, 否 matter 如何 deep 它是 in 树.
相关术语
相关资源
相关课程
- useContext
学习上下文 API for 全局数据.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。