【发布时间】:2021-12-03 15:25:40
【问题描述】:
我正在将 react 路由器用于 SPA 仪表板。我现在在仪表板中有这两条路线(Routes.js)。此外,App.js 中的单独路由用于登录页面。
现在它在加载和单击不同路线时可以正常工作。例如,当我单击客户路线(在侧边栏中)时,它会打开右侧同一页面上的客户部分。但是,当我刷新客户页面 localhost:5000/customers 时,它现在作为单独的页面打开。我该如何解决这个问题。
我尝试调试它,但仍然没有运气。 这是一个例子:https://github.com/gouravthakur39/MRE 不幸的是无法在代码沙箱中重现它
Routes.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import Dashboard from "../pages/Dashboard";
import Customers from "../pages/Customers";
const Routes = () => {
return (
<Switch>
<Route path="/home" exact component={Dashboard} />
<Route path="/customers" exact component={Customers} />
</Switch>
);
};
export default Routes;
App.js 的一部分
import { Fragment } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import PrivateRoute from "./private/PrivateRoute";
import Landing from "./pages/Landing";
import Home from "./pages/Home";
import Customers from "./pages/Customers";
function App() {
return (
<Fragment>
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path="/" component={Landing} />
<PrivateRoute exact path="/home" component={Home} />
<PrivateRoute exact path="/customers" component={Customers} />
</Switch>
</BrowserRouter>
</div>
</Fragment>
);
}
export default App;
【问题讨论】:
-
请澄清“在右侧同一页面上打开客户部分”和“现在它作为单独页面打开”的意思。也不清楚这两个代码 sn-ps 是如何相互关联的,如果它们确实存在的话。为什么要渲染重复的路线?
Routes在哪里渲染?我觉得您没有提供此问题的所有相关代码。如果可能的话,您能否尝试创建一个 running 代码框来重现此问题,以便我们实时检查和调试? -
@DrewReese Routes 在主要内容中呈现 `````` 所以基本上,App.js 中的路由是需要渲染显示仪表板的 /home 路由,并且 routes.js 中的路由需要渲染仪表板路由,例如:客户、产品等。
-
这并不能真正回答问题或清除任何问题。什么是“主要内容”?我仍然只看到两组不同的重复路线并且没有关系。换句话说,我是说我们需要更多的上下文。 stackoverflow.com/help/minimal-reproducible-example
-
@DrewReese 你能看看 MRE。 github.com/gouravthakur39/MRE不幸的是,无法在代码沙箱中重现它。
-
我明白了,根据您的代码和
Dashboard组件上的描述,听起来您希望Dashboard和Customers在“/home”路径中呈现“嵌套”。它是否正确?为什么不能在代码盒中重现它?
标签: reactjs react-router react-router-dom