React 路由器 - 如果在 url 中输入父组件路径,如何重定向到子组件

问题描述 投票:0回答:3

当我只写 /questions 时,我想将我的网址重定向到“/questions/1”

reactjs react-router react-router-dom react-router-component
3个回答
11
投票

您可以渲染从一个路径到另一路径的重定向。

如果使用

react-router-dom
v5,请使用
Redirect
组件:

<Redirect from="/questions" to="/questions/1" />

如果使用

react-router-dom
v6,请使用
Navigate
组件:

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

0
投票

有点晚了,但认为这可能对某人有用。

createBrowserRouter([
    path: 'auth',
    children: [
        {
            index: true,
            loader: async () => redirect("/auth/login")
        },
        {
            path: "login",
            element: <Login />
        },
    ]
)]

!!!警告

这可能会导致重定向循环,如果发生这种情况,请检查一个重定向是否没有调用另一个重定向


0
投票

你必须在react-router-dom v6中使用索引路由

必须像下面这样-

 <Route path="parent" element={<Parent />}>
    <Route index element={<Child1 />} />
    <Route path="child1" element={<Child1 />} />
    <Route path="child2" element={<Child2 />} />
  </Route>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.