我有一个路由设置,如果只给出 1 个参数,即/:id,我希望路由器始终重定向到/:id/overview。
例如,如果用户转到/hello,我希望他们被重定向到/hello/overview。
我试过这样做:
<Switch>
<Route exact path="/" component={NoParam} />
<Redirect from="/:section" to="/:section/overview" />
<Route exact path="/:section/:pageName" component={GeneralOverviewPage} />
</Switch>
这会导致无限重新渲染。我不确定如何实现此重定向,非常感谢任何帮助。谢谢。
编辑=======
现在尝试这样做:
const GeneralOverviewPage: FC<RouteComponentProps<GeneralOverviewPageProps>> = (
props
) => {
console.log(props);
return !props.match.params.pageName ? (
<Redirect to={props.match.params.section + '/overview'} />
) : (
<h1>{props.match.params.pageName}</h1>
);
};
export default GeneralOverviewPage;
和
<Route path="/:section" component={GeneralOverviewPage} />
<Route path="/:section/:pageName" component={GeneralOverviewPage} />
这意味着/hello 现在正在重定向到/hello/hello/overview....
最佳答案
这将帮助您理解!
import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom'
const App = () => {
return (
<Switch>
<Route exact path="/" render={
() => console.log("Hi")
} />
<Redirect exact from="/:section" to="/:section/overview" render={
() => console.log("Hi 1")
} />
<Route exact path="/:section/:pageName" render={
() => console.log("Hi 2")
} />
</Switch>
)
}
export default App;
关于reactjs - 如何默认为基于 URL 参数的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64155809/