You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一组件中初始化并使用React Context?

能否在同一组件中初始化Context Provider并使用该Context?

我有一个名为SortContext的Context,希望在同一个组件中既初始化它的Provider,又直接使用这个Context,请问是否可行?


示例代码1:无法获取Provider提供的值

export default function MyComponent ({children}) {
    const mySortValue = useContext(SortContext)

    return (
        <SortContext.Provider value={'exampleValue'}>
            {children}
        </SortContext.Provider>
    )
}

这段代码中,mySortValue无法获取到'exampleValue'——因为useContext钩子在组件渲染初期就执行了,此时SortContext.Provider还未完成渲染,当前组件并不在Provider的作用域范围内。


示例代码2:Hook使用违反规则

export default function MyComponent ({children}) {
    return (
        <SortContext.Provider value={'exampleValue'}>
            <SortContext.Consumer>
                {context => {
                   const mySortValue = useContext(SortContext)
                   return children
                }}
            </SortContext.Consumer>
        </SortContext.Provider>
    )
}

这种写法完全不可行:SortContext.Consumer的回调函数并非React组件,不符合Hook的使用规则(Hook只能在React函数组件或自定义Hook的顶层调用),因此不能在其中调用useContext。


我知道可以在SortContext.Provider内部新建一个子组件来访问Context,但能不能在单个组件内完成这件事?

补充说明

我使用这个Context来定义数据排序规则,希望Provider覆盖的所有组件都能访问该排序数据。现在想在单个组件中同时实现排序按钮、数据列表和排序逻辑,新建两个组件感觉有些冗余。


内容的提问来源于stack exchange,提问作者William Convertino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:33:28