PHP前端开发

React Context API:综合指南

百变鹏仔 3天前 #JavaScript
文章标签 指南

介绍

react context api 是一种在多个组件之间共享状态的方法,无需通过组件树的每个级别传递数据。 react context api 本质上创建了一个数据层,允许组件订阅和访问数据,而无需成为提供数据的组件的直接子组件。

为什么使用 react context api

上下文 api 创建了一个可通过整个应用程序访问的全局状态,从而导致组件中的简单且结构化的数据流,并使漏洞代码更清晰、更有组织。

了解基础知识

通过整篇文章,为了简单起见,我们将创建一个全局主题上下文。

创建上下文

我们将创建一个名为 themecontext.jsx 的文件,并在其中传递以下逻辑。

创建上下文可以通过简单的步骤完成,即使用默认选项导入和调用createcontext

import {createcontext} from 'react'export const themecontext = createcontext('light')

我们还需要更改主题模式,因此我们将在默认选项中添加一个功能。

import {createcontext} from 'react'export const themecontext = createcontext({      theme: 'light',       settheme: () => {}})

创建提供者

为了让我们的上下文 api 可以通过所有组件访问,我们需要创建一个提供程序,然后使用上下文提供程序包装我们的应用程序或其中的一部分。在这种情况下,我们将包装整个应用程序。

大多数上下文 api 逻辑也将位于提供程序内部,对于我们的情况,我们只需要一个 usestate 来更改主题模式,但可以将更昂贵的逻辑放置在上下文提供程序中。

步骤:

import {usestaet} from 'react'export const themeprovider = ({children}) =&gt; {  const [theme, settheme] = usestate('light')  return (    <themecontext.provider value="{{theme," settheme>      {children}    </themecontext.provider>  )}

下一步是转到应用程序的起点,这适用于我们的案例,您可以根据您的用例选择其他位置。
导入 themeprovider 并用我们的上下文提供程序包装 。此步骤确保主题、settheme 状态可通过整个应用程序访问。

createroot(document.getelementbyid('root')!).render(  <strictmode><themeprovider><app></app></themeprovider></strictmode>,)

消费提供者

现在在任何其他组件中,我们需要从react调用usecontext,从themecontext.jsx文件调用themecontext。

然后解构主题,设置主题值并在你的组件中使用它们。

import {usecontext} from 'react'import {themecontext} from './themecontext'const app = () =&gt; {    const {theme, settheme} = usecontext(themecontext)  // some logic to change background color here  return(   <div>     <button onclick="{()"> settheme("light")}&gt;light</button>     <button onclick="{()"> settheme("dark")}&gt;dark</button>   </div>  )}export default app;

使用自定义 react hook 增强 context api

ps:我已经创建了一篇关于 react 中自定义钩子入门的帖子,如果您有任何问题,请点击这里

我们可以通过定义自定义react hook来避免从react和themecontext调用usecontext。
在 themecontext.jsx 文件中创建一个名为 usetheme
的自定义钩子

const usetheme = () =&gt; {  const context = usecontext(themecontext)  if (!context) throw new error('something went wrong!')  return context}

在其他组件中只需导入这个自定义钩子

import {useTheme} from 'themeContext'const App = () =&gt; {  const {theme, setTheme} = useTheme()  return(...)}

结论

在本指南中,我们深入了解了上下文 api,并演示了它在跨应用程序组件传输数据方面的功效。我们创建了一个上下文及其提供程序,并将我们的应用程序与上下文提供程序包装在一起,并学习如何使用提供程序,甚至通过使用自定义挂钩来增强代码。

感谢您的阅读