小编joh*_*n23的帖子

在 React 中使用另一个上下文中的上下文

目前,我的 React 应用程序中有 2 个上下文,我试图在第二个上下文中从顶级上下文调用一个方法。

以下是上下文的嵌套方式:

应用程序.js

function App(props) {

  return (
    <SessionContextProvider>
      <APIContextProvider>
         // I have some components here
      </APIContextProvider>
    </SessionContextProviders>
  )
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在我的 APIContextProvider 中使用 SessionContext?

import { SessionContext } from 'contexts/session'

export const APIContext = createContext();

export default class APIContextProvider extends Component {

    static contextType = SessionContext

    randomMethod() {
        this.context.logoutUser()
    }

    render() {
        return (
            <APIContext.Provider value={{randomMethod: this.randomMethod}}>
                {this.props.children}
            </APIContext.Provider>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,在我的 APIContext 中运行 randomMethod 时不起作用,因为 this.context 未定义。

这是可行的还是我错过了什么?

reactjs react-hooks

3
推荐指数
1
解决办法
9686
查看次数

标签 统计

react-hooks ×1

reactjs ×1