简体   繁体   English

不能使用 React 上下文?

[英]Can't use React context?

My index.js has:我的index.js有:

ReactDOM.render(
    <FirebaseContext.Provider value={new Firebase()}>
        <Suspense fallback="loading">
            <App/>
        </Suspense>
    </FirebaseContext.Provider>,
    document.getElementById('root')
);

Inside app.js I am trying to access the context:app.js中,我试图访问上下文:

export default function App(props) {
    console.log("app trying to use firebase");
    const {firebase} = useFirebase();
    return <div>{firebase && firebase.loggedIn()}</div>
}

FirebaseContext and Firebase class are defined like so: FirebaseContext 和 Firebase class 定义如下:

export const FirebaseContext = createContext({});
export const useFirebase = () => useContext(FirebaseContext);

export default class Firebase {
    constructor() {
        console.log("firebase intialized")
        app.initializeApp(firebaseConfig);
        this.auth = app.auth();
    }

    loggedIn = () => {
        return !!this.auth.currentUser;
    }
}

FirebaseContext seems to be initialized properly since I get the output inside the console, but I keep getting Error: Cannot read property 'loggedIn' of undefined. FirebaseContext 似乎已正确初始化,因为我在控制台内获得了 output,但我不断收到错误:无法读取未定义的属性“loggedIn”。 Why can't I use my context?为什么我不能使用我的上下文?

Have you tried your code after removing the destructuring like so像这样删除解构后,您是否尝试过代码

const {firebase} = useFirebase(); =>>> const firebase = useFirebase(); =>>> const firebase = useFirebase();

If the issue persists, then try to bind the firebase variable given that loggedIn is resulting in undefined within a class-based component.如果问题仍然存在,请尝试绑定firebase变量,因为loggedIn 导致在基于类的组件中未定义。

Context.Provider上下文提供者

<MyContext.Provider value={/* some value */}>

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.每个 Context object 都带有一个 Provider React 组件,允许消费组件订阅上下文更改。

The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. Provider 组件接受要传递给作为此 Provider 后代的消费组件的 value prop。 One Provider can be connected to many consumers.一个提供者可以连接到多个消费者。 Providers can be nested to override values deeper within the tree.可以嵌套提供程序以覆盖树中更深的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM