Reactjs 如何基于URL参数默认路由
我有一个路由设置,如果只给出1个参数,即/:id,我希望路由器总是重定向到/:id/概览 例如,如果用户转到/hello,我希望他们被重定向到/hello/overview 我试过这样做:Reactjs 如何基于URL参数默认路由,reactjs,react-router,Reactjs,React Router,我有一个路由设置,如果只给出1个参数,即/:id,我希望路由器总是重定向到/:id/概览 例如,如果用户转到/hello,我希望他们被重定向到/hello/overview 我试过这样做: <Switch> <Route exact path="/" component={NoParam} /> <Redirect from="/:section" to="/:section/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;
这会导致无限重渲染。我不知道如何实现这个重定向,非常感谢您的帮助。谢谢
编辑=======
现在试着这样做:
<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;
const generaloverview页面:FC=(
道具
) => {
控制台日志(道具);
return!props.match.params.pageName(
) : (
{props.match.params.pageName}
);
};
导出默认的GeneralOverview页面;
及
这意味着/hello现在正在重定向到/hello/hello/overview…您的
必须位于GeneralOverviewPage
组件内
if(!pageName){
return (<Redirect from="/:section" to="/:section/overview" />);
}
if(!pageName){
返回();
}
这将帮助您理解
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;
从“React”导入React;
从“react router dom”导入{交换机、路由、重定向}
常量应用=()=>{
返回(
控制台日志(“Hi”)
} />
控制台日志(“Hi 1”)
} />
控制台日志(“Hi 2”)
} />
)
}
导出默认应用程序;
不是React方面的专家,所以如果我错了,请原谅我,但是您不想在重定向中添加确切的关键字吗?另外;身份验证问题也可能导致此类问题嗨,伙计们,我想以编程方式使用传递给route@Daniel,我尝试了其他方法(我将编辑og帖子),但仍然不起作用。不幸的是,这将我重定向到:部分/overview@Raph117您的路线中不会有两个属性?然后使用下一个模式:'/section/:section/page/:pageName',并且您的url必须为test.com/section/sectionKey/page/page1。做正确的分割。这对我来说很有效,我完全不知道如何分割,因为这是我一开始做的。无论如何,谢谢你!查看此以了解更多信息