gpt4 book ai didi

reactjs - 使用 useContext 钩子(Hook)时如何访问提供者值

转载 作者:行者123 更新时间:2023-12-03 14:07:13 27 4
gpt4 key购买 nike

import React, { useContext } from 'react'
import { MyContext, MyProvider } from './Context'

const MasterContainer = () =>{
const ctx = useContext(MyContext)

return (
<MyProvider>
{ctx}
<MyContext.Consumer>
{context=><div>{context.age}</div>}
</MyContext.Consumer>
</MyProvider>
)
}

export default MasterContainer

当我真正想要拉取 ctx.age 时,ctx 现在返回未定义

import React from 'react'


export const MyContext = React.createContext("dude")

export class MyProvider extends React.Component{
state = {
name: 'Hello',
age: 12
}
render(){
return (
<MyContext.Provider value={this.state}>
{this.props.children}
</MyContext.Provider>
)
}
}

基本上我想使用钩子(Hook)访问我的提供程序中我的状态值,我该怎么做?

最佳答案

这是 createContext 方法和更新当前上下文值的一个非常简单的用例。 CodeSandbox-example

这里需要注意,如 React.js createContext-method documentation 中所述。 ,上下文值将与树中上面最接近的匹配 Provider 进行匹配。

React.createContext - Creates an Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

另请记住,如文档中所述,仅当未找到匹配的提供程序时才使用默认值参数。

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing undefined as a Provider value does not cause consuming components to use defaultValue.

关于reactjs - 使用 useContext 钩子(Hook)时如何访问提供者值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53089554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com