reactjs – 我可以用钩子替换上下文吗?
有没有办法使用新的反应钩子API来替换上下文数据获取?
如果您需要加载用户配置文件并在几乎所有地方使用它,首先创建上下文并将其导出: export const ProfileContext = React.createContext() 然后导入顶级组件,加载数据并使用提供程序,如下所示: import { ProfileContext } from 'src/shared/ProfileContext' <ProfileContext.Provider value={{ profile: profile,reloadProfile: reloadProfile }} > <Site /> </ProfileContext.Provider> 然后在其他一些组件中导入配置文件数据,如下所示: import { ProfileContext } from 'src/shared/ProfileContext' const context = useContext(profile); 但是有一种方法可以使用钩子导出一些函数,这些钩子将具有状态和共享配置文件以及任何想要获取数据的组件? 解决方法
React提供了一个useContext钩子来使用Context,它具有类似的签名
const context = useContext(Context);
您可以在组件中使用它 import { ProfileContext } from 'src/shared/ProfileContext' const Site = () => { const context = useContext(ProfileContext); // make use of context values here } 但是,如果你想在每个组件中使用相同的上下文而不想在任何地方导入ProfileContext,你可以简单地编写一个自定义钩子 import { ProfileContext } from 'src/shared/ProfileContext' const useProfileContext = () => { const context = useContext(ProfileContext); return context; } 并在组件中使用它 const Site = () => { const context = useProfileContext(); } 然而,就创建一个在不同组件之间共享数据的钩子而言,Hooks有一个自己的数据实例,除非你使用Context,否则不要共享它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |