gpt4 book ai didi

javascript - React Router v6.4.5,页面加载重定向

转载 作者:行者123 更新时间:2023-12-05 04:19:41 27 4
gpt4 key购买 nike

寻求有关重定向的帮助。以下是代码片段。

索引.js

const router = createBrowserRouter([

{
//set App as root element...
path: "/",
loader: () => {

},
element: <App/>,
errorElement: <ErrorPage/>,

//set routes for child elements...
children: [
{
path: "/home",
element: <Home/>
},
{
path: "/about",
element: <About/>,
errorElement: <ErrorPage/>
},
{
path: "/blog",
element: <Blog/>,
errorElement: <ErrorPage/>
},
{
path: "/services",
element: <Services/>,
errorElement: <ErrorPage/>
}

]
}
])

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<RouterProvider router={router} />
{/* <App /> */}
</React.StrictMode>
);

App.js

import React from "react";
import { BrowserRouter, Outlet, redirect, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./views/Home";


function App() {

return (

<div className="App">
<Navbar/>
<Outlet/>
</div>
);
}

export default App;

我想要做的就是在页面加载“./”作为根目录时将页面从“localhost:3000/”重定向到“localhost:3000/home”,这样我就可以呈现应用程序主页。在我使用 socket 的地方,我希望它在那里呈现并始终呈现导航栏。我在文档中没有看到 createBrowserRouter 的重定向选项。

最佳答案

您可以通过 Navigate 呈现从 "/""/home" 的重定向组件和 replace 属性。

例子:

const router = createBrowserRouter([
{
//set App as root element...
path: "/",
loader: () => { ... },
element: <App />,
errorElement: <ErrorPage />,

//set routes for child elements...
children: [
{
index: true, // <-- match on parent, i.e. "/"
element: <Navigate to="/home" replace /> // <-- redirect
},
{
path: "/home",
element: <Home />
},
{
path: "/about",
element: <About />,
errorElement: <ErrorPage />
},
{
path: "/blog",
element: <Blog />,
errorElement: <ErrorPage />
},
{
path: "/services",
element: <Services />,
errorElement: <ErrorPage />
}
]
}
]);

关于javascript - React Router v6.4.5,页面加载重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74737857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com