useContext
一句话解释
useContext 是 Hook 那个 lets 组件读取 and subscribe 到上下文值 不使用 manually passing Props 通过每个 level.
用大白话说
useContext solves the problem of prop drilling — passing data through many layers of components that don't need it themselves, just to reach a deeply nested child.
First you create a Context with React.createContext(defaultValue). A parent provides the value with <MyContext.Provider value={...}>. Any descendant, no matter how deep, can read it with const value = useContext(MyContext).
When the Provider's value changes, all components calling useContext with that context re-render. This makes Context great for themes, user authentication, locale, and other app-wide data. For frequently changing values, be aware that all consumers re-render on every change.
示例
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click</button>;
}Toolbar 读取主题 directly 从上下文不使用接收它 as prop. Provider in App supplies 值.
相关术语
相关资源
相关课程
- useContext
学习上下文 and useContext for 全局数据.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。