问题描述
当用户在URI(在浏览器中)上键入时,我正在尝试实现不匹配或无效路由。以下是我的路由器组件。
当URI <Redirect/>
重定向到localhost:9090/{something}
页时,在\
下工作,但是当 URI无效(如localhost:9090/{invalidyyy}/{invalidxx}
)未显示时,屏幕。请帮助/建议我克服相同的问题。
更新:我在App组件内部渲染以下组件,
App.js
render(){
return( <RenderRoutes/> )
}
const renderRoutes = () => {
console.log('isAuthrenderRoute',isAuth);
return (
<Router>
<div>
<Switch>
<Route
exact
path="/"
render={props => (
<AppRoute Component={Login} props={props} />
)}
/>
<Route
exact={true} path="/xxx/ForgotPassword"
render={props => (
<LandingPage>
<AppRoute Component={ForgotPassword} props={props} />
</LandingPage>
)}
/>
<Redirect exact to="/" />
</Switch>
</div>
</Router>
);
};
const AppRoute = ({ Component,Layout,props }) => {
if (Layout) {
return (
<Layout {...props}>
<Component {...props} />
</Layout>
);
}
if (!Component) {
return <Layout {...props} />;
}
return <Component {...props} />;
};
export default renderRoutes;
解决方法
Switch
组件将呈现与路由条件匹配的第一个组件。为了使其正常工作,应仅将<Route />
组件用作子组件。 <Redirect />
起作用的原因是,当所有路由都不匹配时,由于它不是路由,它将回退到重定向组件。
您现在将<LandingPage>
组件呈现为<Switch>
组件的子组件。这导致该组件始终由Switch呈现。但是,该页面将为空,因为“路线”组件与当前位置不匹配。
这是您应该运行的代码:
const renderRoutes = () => {
return (
<Router>
<div>
<Switch>
<Route
exact
path="/"
render={props => (
<AppRoute Component={Login} props={props} />
)}
/>
{(isAuth !== null || isAuth !== false) && (
<Route
exact={true} path="/xxx/ForgotPassword"
render={props => (
<LandingPage>
<AppRoute Component={ForgotPassword} props={props} />
</LandingPage>
)}
/>
)}
<Redirect exact to="/" />
</Switch>
</div>
</Router>
);
};