尝试部署我的网站时,遇到以下错误:

Warning: Failed context type: The context `router` is marked as required in `Switch`, but its value is `undefined`.
    in Switch (created by SignIn)
    in div (created by SignIn)
    in div (created by SignIn)
    in SignIn (created by LogonPage)
    in div (created by LogonPage)
    in div (created by LogonPage)
    in LogonPage
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Provider


随着

Uncaught Invariant Violation: You should not use <Switch> outside a <Router>


通常,我会确定问题出在哪里-受影响节点的父节点某处缺少路由器。

但是,在我的情况下,SignIn呈现如下:

    return (
        <div className="signInContainer container">
            <div className="signInMethodPicker row">
                <Link to="/register" className="signInMethodBtn registerBtn col">{Translation.Register}</Link>
                <Link to="/login" className="signInMethodBtn loginBtn col">{Translation.Login}</Link>
            </div>
            <hr />
            <div>
                <Switch>
                    <Route exact path="/" render={props => <RegisterDialog {...props} />} />
                    <Route exact path="/register" render={props => <RegisterDialog {...props} />} />
                    <Route exact path="/login" render={props => <LoginDialog {...props} />} />
                </Switch>
            </div>
        </div>
    );


在此处的入口点还有给定的路由器:

$(() => {
    ReactDOM.render(
        <Provider store={store}>
            <BrowserRouter>
                <LogonPage />
            </BrowserRouter>
        </Provider>,
        document.getElementById("logonPageHolder"));
});


路由器是这样导入的:import { BrowserRouter } from "react-router-dom";

两者之间存在一层,但考虑到我最近重新编写了我的应用程序,并且以前可以正常工作,所以我看不出有什么问题。

鉴于我最近的重写,我高度怀疑此问题是基于奇怪的版本控制,但是我仍然需要一些指导来解决此问题,因为研究此错误通常只会给我结果,这表明人们实际上忘记渲染<Router>组件,此处不是这种情况。

最佳答案

您需要使用BrowserRouter或其他替代方法(如HashRouter,MemoryRouter)包装Switch。

尝试这样做

import { BrowserRouter, Switch, Route } from 'react-router-dom';


然后把所有东西包起来

<BrowserRouter>
 <Switch>
  //your routes here
 </Switch>
</BrowserRouter>

10-08 00:52