加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 我可以用钩子替换上下文吗?

发布时间:2020-12-15 09:31:47 所属栏目:百科 来源:网络整理
导读:有没有办法使用新的反应钩子API来替换上下文数据获取? 如果您需要加载用户配置文件并在几乎所有地方使用它,首先创建上下文并将其导出: export const ProfileContext = React.createContext() 然后导入顶级组件,加载数据并使用提供程序,如下所示: import {
有没有办法使用新的反应钩子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);

useContext accepts a context object (the value returned from
React.createContext) and returns the current context value,as given
by the nearest context provider for the given context.

When the provider updates,this Hook will trigger a rerender with the
latest context value.

您可以在组件中使用它

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,否则不要共享它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读