ChatGPT解决这个技术问题 Extra ChatGPT

如何在 React Router 中将 DefaultRoute 设置为另一个路由

我有以下内容:

  <Route name="app" path="/" handler={App}>
    <Route name="dashboards" path="dashboards" handler={Dashboard}>
      <Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
      <Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
      <DefaultRoute handler={DashboardExplain} />
    </Route>
    <DefaultRoute handler={SearchDashboard} />
  </Route>

使用 DefaultRoute 时,SearchDashboard 呈现不正确,因为任何 *Dashboard 都需要在 Dashboard 中呈现。

我希望“app”路由中的 DefaultRoute 指向路由“searchDashboard”。这是我可以用 React Router 做的事情,还是我应该为此使用普通的 Javascript(用于页面重定向)?

基本上,如果用户转到主页,我想将它们发送到搜索仪表板。所以我想我正在寻找与 window.location.replace("mygreathostname.com/#/dashboards/searchDashboard"); 等效的 React Router 功能

您是否尝试过使用 Redirect 而不是 DefaultRoute ?
@JonatanLundqvistMedén 这正是我想要的,谢谢!把它写成答案,我会把它标记为正确的。回复较晚,抱歉。

O
Ogglas

您可以使用重定向而不是 DefaultRoute

<Redirect from="/" to="searchDashboard" />

感谢 Ogglas,更新 2019-08-09 以避免出现刷新问题

<Redirect exact from="/" to="searchDashboard" />

资源:

https://stackoverflow.com/a/43958016/3850405


只是我,还是使用它直接点击深层网址时,我总是被重定向到“到”网址,而不是我试图点击的路线?
应该注意的是,如果您正在执行一些重定向,例如 from='/a' to='/a/:id',您将需要使用 <Switch> 来包含来自 react-router 的 <Redirect><Route> 组件。详情见doc
@Kulbear 我有同样的问题。做奥格拉斯在他的回答中所说的工作是有效的。
要使其正常工作,您很可能需要将此路线放在最后或执行此操作<Redirect exact from="/" to="/adaptation" />
监督它很容易,所以我重复一遍:DarkWalker 重定向规则的重要部分是 exact 标志。接受的答案缺少这一点,因此它与 [几乎] 任何路线匹配。
O
Ogglas

更新:

对于 v6,您可以使用 Navigate 执行此操作。您可以使用“不匹配”路由来处理“不匹配”情况。

<Routes>
  <Route path="/" element={<Navigate to="/searchDashboard" />}>
    <Route path="searchDashboard" element={<SearchDashboard/>} />
    <Route
      path="*"
      element={<Navigate to="/" />}
    />
  </Route>
</Routes>

https://reactrouter.com/docs/en/v6/getting-started/tutorial#adding-a-no-match-route

https://stackoverflow.com/a/69872699/3850405

原来的:

使用 <Redirect from="/" to="searchDashboard" /> 的问题是,如果您有不同的 URL,例如 /indexDashboard,并且用户点击刷新或收到发送给他们的 URL,则无论如何用户将被重定向到 /searchDashboard

如果您不希望用户能够刷新站点或发送 URL,请使用以下命令:

<Route exact path="/" render={() => (
    <Redirect to="/searchDashboard"/>
)}/>

如果 searchDashboard 落后于登录,请使用此选项:

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/searchDashboard"/>
  ) : (
    <Redirect to="/login"/>
  )
)}/>

S
Seth

我错误地尝试使用以下命令创建默认路径:

<IndexRoute component={DefaultComponent} />
<Route path="/default-path" component={DefaultComponent} />

但这会创建两个不同的路径来呈现相同的组件。这不仅没有意义,而且会导致您的 UI 出现故障,即,当您根据 this.history.isActive() 设置 <Link/> 元素的样式时。

创建默认路由(不是索引路由)的正确方法是使用 <IndexRedirect/>

<IndexRedirect to="/default-path" />
<Route path="/default-path" component={DefaultComponent} />

这是基于 react-router 1.0.0。请参阅https://github.com/rackt/react-router/blob/master/modules/IndexRedirect.js


对已经由您的 IndexRoute 处理的内容添加 Route 有什么意义?
没有意义,我编辑了我的答案,以明确表示我不提倡这样做。
这也是我一直在做的事情,但我喜欢在 / 提供组件(我的主页)的解决方案,而不必重定向到例如 /home
T
Thanveer Shah

更新:2020

无需使用重定向,只需在 path 中添加多个路由

例子:

<Route exact path={["/","/defaultPath"]} component={searchDashboard} />

嘿,你确定那里有方括号吗?因为我收到错误:"Uncaught TypeError: meta.relativePath.startsWith is not a function" ,所以当我删除方括号时,它工作正常,如下所示:<Route exact path={"/","/defaultPath"} component={searchDashboard} />
d
dwilt

乔纳森的回答似乎对我不起作用。我正在使用 React v0.14.0 和 React Router v1.0.0-rc3。这做到了:

<IndexRoute component={Home}/>

所以在马修的案例中,我相信他会想要:

<IndexRoute component={SearchDashboard}/>

来源:https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle.md


感谢您的分享。我为此使用了 React v0.13 和 React-Router 版本,所以是 1.0/rc 之前的版本。希望这对其他人有帮助!
我认为这会让你失去上下文。 SearchDashboard 将是您到达主页时将看到的组件,但如果您直接转到 /dashboard/searchDashboard,则不会是包装它的 Dashboard 组件。 React-router 根据 URL 匹配的路由动态构建嵌套组件的层次结构,因此我认为您确实需要在这里进行重定向。
B
Bijan Kundu

由于最近发布了 V6,因此接受的答案将不起作用,因为 V6 中不再存在 Redirect。考虑使用导航。

 <Route path="/" element={<Navigate to="/searchDashboard" />} />

参考:- V6 docs


佚名
import { Route, Redirect } from "react-router-dom";

class App extends Component {
  render() {
    return (
      <div>
        <Route path='/'>
          <Redirect to="/something" />
        </Route>
//rest of code here

这将使得当您在本地主机上加载服务器时,它会将您重定向到 /something


d
devil_io

我遇到了类似的问题;如果没有一个路由处理程序匹配,我想要一个默认路由处理程序。

我的解决方案是使用通配符作为路径值。即还要确保它是您的路线定义中的最后一个条目。

<Route path="/" component={App} >
    <IndexRoute component={HomePage} />
    <Route path="about" component={AboutPage} />
    <Route path="home" component={HomePage} />
    <Route path="*" component={HomePage} />
</Route>

K
Kevin Hernandez

对于即将进入 2017 年的用户,这是使用 IndexRedirect 的新解决方案:

<Route path="/" component={App}>
  <IndexRedirect to="/welcome" />
  <Route path="welcome" component={Welcome} />
  <Route path="about" component={About} />
</Route>

h
hadeneh

2022 年 5 月

导入导航

import { Routes, Route, Navigate } from 'react-router-dom';

添加

<Route path="/" element={<Navigate replace to="/home" />} />

例如:

import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';

import Home from './pages/Home';
import Login from './pages/Login';

const Main = () => {
    return (
        <Routes>
            <Route path="/" element={<Navigate replace to="/home" />} />
            <Route path='home' element={<Home />}></Route>
            <Route path='login' element={<Login />}></Route>
        </Routes>
    );
}

export default Main;

完毕!


u
user3889017
 <Route name="app" path="/" handler={App}>
    <Route name="dashboards" path="dashboards" handler={Dashboard}>
      <Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
      <Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
      <DefaultRoute handler={DashboardExplain} />
    </Route>
    <Redirect from="/*" to="/" />
  </Route>

react-router v4 中的 DefaultRoute 是什么?
@AnthonyKong 我认为是: <Route exact path="/" component={Home}/>reacttraining.com/react-router/web/example/basic
M
Marc Costello

首选方法是使用 react router IndexRoutes 组件

你像这样使用它(取自上面链接的反应路由器文档):

<Route path="/" component={App}>
    <IndexRedirect to="/welcome" />
    <Route path="welcome" component={Welcome} />
    <Route path="about" component={About} />
</Route>

链接页面现在给 404
n
nipundimantha

首先你需要安装:

npm install react-router-dom;

然后你需要使用你的 App.js(在你的情况下它可以不同)并进行下面的修改。在这种情况下,我选择了重定向来获得正确的渲染过程。

import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";

<Router>
        <Suspense fallback={<Loading />}>
          <Switch>
            <Route exact path="/">
              <Redirect to="/Home" component={Routes.HomePage}/>
            </Route>
            <Route exact path="/Biz" component={Routes.Biz} />
          </Switch>
        </Suspense>
      </Router>

您成功地进行了上面的修改,您可以看到重定向 URL 在您的浏览器路径上,并且渲染过程也根据它们的组件正常工作。

前段时间,我们有机会在 react 路由中使用了名为“DefaultRoute”的组件。

现在,它的折旧方法,并且使用它不是很流行,您可以创建名为 default 或其他名称的自定义路由,但仍然不是我们在现代 React.js 开发中这样做的方式。

只是因为使用“DefaultRoute”路由,我们可能会导致一些渲染问题,这是我们绝对希望避免的事情。


p
prakhar tomar

这是我的做法-

<Router>
  <div className="App">
    <Navbar />
    <TabBar />
    <div className="content">
      <Route exact path={["/default", "/"]}> //Imp
        <DefStuff />
      </Route>
      <Route exact path="/otherpage">
        <Otherstuff />
      </Route>
      <Redirect to="/defult" /> //Imp
    </div>
  </div>
</Router>

B
Bar Horing Amir

利用:

<Route path="/" element={<Navigate replace to="/expenses" />} />

在上下文中:

import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";

<BrowserRouter>
  <Routes>
    <Route element={<App />}>
      <Route path="/expenses" element={<Expenses />} />
      <Route path="/invoices" element={<Invoices />} />
    </Route>
    <Route path="/" element={<Navigate replace to="/expenses" />} />
  </Routes>
</BrowserRouter>

s
surbhi241

您可以像这样使用它来重定向特定的 URL,并在从旧路由器重定向到新路由器后渲染组件。

<Route path="/old-router">
  <Redirect exact to="/new-router"/>
  <Route path="/new-router" component={NewRouterType}/>
</Route>