【问题标题】:How to default to a route based on a URL parameter如何根据 URL 参数默认路由
【发布时间】:2021-01-17 04:50:34
【问题描述】:

我有一个路由设置,如果只给出 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....

【问题讨论】:

  • 不是 React 专家,如果我错了,请原谅我,但您不想将确切的关键字添加到重定向吗?
  • 还有;身份验证问题也可能导致此类问题
  • 大家好,我想以编程方式使用传递给路由的部分
  • @Daniel,我尝试了其他方法(我将编辑 og 帖子)但仍然无法正常工作

标签: reactjs react-router


【解决方案1】:

这将帮助您理解!

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;

【讨论】:

  • 这现在对我有用,我对如何做的理解准确为 0,因为这是我首先做的。无论如何,谢谢!
  • 通过此了解更多信息Reference
【解决方案2】:

您的&lt;Redirect from="/:section" to="/:section/overview" /&gt; 必须在GeneralOverviewPage 组件内。

if(!pageName){
  return (<Redirect from="/:section" to="/:section/overview" />);
}

【讨论】:

  • 不幸的是,这将我重定向到:section/overview
  • @Raph117 你的路线不会有两个属性吗?比使用下一个模式:'/section/:section/page/:pageName' 你的 url 必须是 test.com/section/sectionKey/page/page1。进行正确的拆分。
猜你喜欢
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2016-08-21
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
相关资源
最近更新 更多