簡體   English   中英

反應樹中未定義的上下文

[英]Undefined context in the react tree

我到處都收到未定義的 static 上下文,我錯過了什么? 路由器會以某種方式影響它,或者我只是忘記了一些小部分。 這個想法是定義用戶瀏覽器並在我的所有組件中分配結果真/假。 謝謝

    class App extends Component {

    static contextType = GlobalContext;

    isBrowserChrome = () => {
        return window.navigator.userAgent.indexOf('Chrome') !== -1;
    };



    render() {
        return (
            <GlobalProvider isChrome={this.isBrowserChrome()} >
            <AppLayout>
                <PageLayout>
                    <Loading/>
                    <PureModal/>
                    <ContentLayout>
                            <DashboardLayout>
                                {this.props.auth.authenticated && <EpMenu/> }
                                <div style={{marginTop: '20px'}}>
                                    <Switch>
                                        <Route exact path="/login/:token?" component={LoginPage}/>
                                        <PrivateRoute exact path="/welcome" component={Welcome}/>
                                    </Switch>
                                </div>
                            </DashboardLayout>
                    </ContentLayout>
                </PageLayout>
            </AppLayout>
            </GlobalProvider>
        );
    }
}

App.contextType = GlobalContext;

export default App;

導出 const GlobalContext = React.createContext(false);

export class GlobalProvider extends Component {

    render() {
        return (
            <GlobalContext.Provider value={this.props.isChrome}>
                {this.props.children}
            </GlobalContext.Provider>
        )
    }
}

您必須使用contextconsumer才能使用上下文值

請在下面的鏈接中找到上下文 API 的參考:

https://reactjs.org/docs/context.html#contextconsumer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM