为什么分配给默认值的上下文值?

发布于 2025-01-28 19:54:29 字数 393 浏览 2 评论 0原文

为什么在提供商中使用了值支柱,为什么分配给默认值的上下文值? 这是当我创建上下文时:

export let exchangeContext=React.createContext();

我在同一组件中创建了提供商

 <exchangeContext.Provider value={"aya"}>  </exchangeContext.Provider>

,当我安装消费者中的值时,我会被不确定为默认值

 <exchangeContext.Consumer>
       {(value)=>{
         console.log(value)

why do the context value assigned to default value despite of using value prop in provider??
here is when I created the context:

export let exchangeContext=React.createContext();

I created provider in the same component

 <exchangeContext.Provider value={"aya"}>  </exchangeContext.Provider>

and when I console log the value in the consumer i get undefined as the default value

 <exchangeContext.Consumer>
       {(value)=>{
         console.log(value)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

毁梦 2025-02-04 19:54:29

不必写消费者

消费者是usecontext挂钩是一件事情之前的旧方法),则

import { exchangeContext } from './App' // wherever the main context is

如果您使用上下文(

const value = React.useContext(exchangeContext)

return <>{value}</>

写作 ://reactjs.org/docs/hooks-reference.html#usecontext“ rel =” nofollow noreferrer“> https://reactjs.s.org/docs/hooks/hooks-reference.html#usecontext

You don't have to write consumer if you used context (writing consumer is the old way before useContext hook was a thing)

In your consumer file do this

import { exchangeContext } from './App' // wherever the main context is

then in your function body

const value = React.useContext(exchangeContext)

then in your return body

return <>{value}</>

see: https://reactjs.org/docs/hooks-reference.html#usecontext for more info

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文