我正在使用最新的 React Router ( 4 ) 版本。我的路线有一个动态配置,就像教程中描述的那样。它工作正常但是当我尝试添加 404 路径时(就像在教程中一样)它开始显示这个 404 页面就在加载任何具有正确路径的普通组件之前。
如果路径不存在,404 路由会正常工作。
在移动到允许的路由配置的情况下)
首先 - 显示 404 组件(我不知道为什么) 第二 - 正常组件显示,404 组件消失。
有没有人知道如何解决这个问题?感谢您提供任何信息!
这是我的路由配置。
import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";
const navScheme = Config.navigationScheme;
const COMPLEX_ROUTES = route => {
console.log("routesss ->> ", route);
return (
<Switch >
<Route path={route.path} exact={!!route.exact} render={props => (
// pass the sub-routes down to keep nesting
<route.component {...props} routes={route.routes}/>
)}/>
</Switch>
);
};
const generateRoutes = routes => routes.map((route, i) => (
<COMPLEX_ROUTES key={i} {...route}/>
));
const PLATFORM_CHILD_ROUTES = [
{
path : navScheme.platform,
component : lazyRoute(() => import("../../modules/home/Home.module")),
exact : true
}
];
const ROUTES = [
{
path : navScheme.root,
component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
exact : true
},
{
path : navScheme.platform,
component : lazyRoute(() => import("../components/Platform")),
routes : PLATFORM_CHILD_ROUTES
},
{
path : "*",
component : lazyRoute(() => import("../../modules/errors/Error404.module"))
},
];
export { generateRoutes, ROUTES };
最佳答案
我已经找到了这个问题的解决方案。
在react-router的文档中我们可以看到:
A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches.
这意味着我们应该将 Switch 组件添加到我们的路由方案中以仅显示第一个匹配的组件。我有 Switch,但放错了地方。它应该包装生成的路由,但在我的例子中它是“内部包装器”。
在这些更改之后,我的配置如下所示:
import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";
const navScheme = Config.navigationScheme;
const COMPLEX_ROUTES = route => {
return (
<Route path={route.path} exact={!!route.exact} render={props => (
// pass the sub-routes down to keep nesting
<route.component {...props} routes={route.routes}/>
)}/>
);
};
const generateRoutes = routes => {
return (
<Switch>
{
routes.map((route, i) => (
<COMPLEX_ROUTES key={i} {...route}/>
))
}
</Switch>
);
};
const PLATFORM_CHILD_ROUTES = [
{
path : navScheme.platform,
component : lazyRoute(() => import("../../modules/home/Home.module")),
exact : true
}
];
const ROUTES = [
{
path : navScheme.root,
component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
exact : true
},
{
path : navScheme.platform,
component : lazyRoute(() => import("../components/Platform")),
routes : PLATFORM_CHILD_ROUTES
},
{
path : "*",
component : lazyRoute(() => import("../../modules/errors/Error404.module"))
},
];
export { generateRoutes, ROUTES };
希望对大家有帮助。 此致。维利丹
关于javascript - 在动态路由的情况下 react 路由器 4 404 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968819/