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

RTW*_*RTW 4 reactjs react-hooks

有没有办法使用新的react hooks API替换上下文数据获取?

如果需要加载用户配置文件并在几乎所有地方使用它,请首先创建上下文并导出它:

export const ProfileContext = React.createContext()
Run Code Online (Sandbox Code Playgroud)

然后导入顶级组件,加载数据并使用提供程序,如下所示:

import { ProfileContext } from 'src/shared/ProfileContext'

<ProfileContext.Provider
      value={{ profile: profile, reloadProfile: reloadProfile }}
    >
        <Site />
    </ProfileContext.Provider>
Run Code Online (Sandbox Code Playgroud)

然后,在其他一些组件中,您可以像这样导入配置文件数据:

import { ProfileContext } from 'src/shared/ProfileContext'
const context = useContext(profile);
Run Code Online (Sandbox Code Playgroud)

但是,有一种方法可以导出带有挂钩的某些函数,这些挂钩将具有状态并与想要获取数据的任何组件共享配置文件?

Shu*_*tri 5

React提供了useContext钩子来使用Context,它的签名类似于

const context = useContext(Context);
Run Code Online (Sandbox Code Playgroud)

useContext 接受一个上下文对象(从React.createContext返回的值)并返回当前上下文值,该值由最近的上下文提供者为给定上下文提供。

提供程序更新时,此挂钩将触发具有最新上下文值的重新呈现。

您可以在组件中使用它,例如

import { ProfileContext } from 'src/shared/ProfileContext'

const Site = () => {
   const context = useContext(ProfileContext);
   // make use of context values here
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您想在每个组件中使用相同的上下文,并且不想导入ProfileContext任何地方,则可以简单地编写一个自定义钩子,例如

import { ProfileContext } from 'src/shared/ProfileContext'
const useProfileContext = () => {
   const context = useContext(ProfileContext);
   return context;
}
Run Code Online (Sandbox Code Playgroud)

并在诸如

const Site = () => {
   const context = useProfileContext();
}
Run Code Online (Sandbox Code Playgroud)

但是,就创建一个在不同组件之间共享数据的挂钩而言,挂钩具有自己的数据实例,除非您使用Context,否则不要共享它。

  • @RTWTMI,是的,您仍然需要顶层的Provider,useContext替代了MyComponent.contextTypes = ProfileContext。 (2认同)