React Router V6.9 重定向
因为react 更新,没有Redirect 标签无法使用
Router官方地址:
https://reactrouter.com/en/main
需要重定向,基础代码如下:
配置router.js
配置基础页面路径:
src/router/index.js
import React from 'react'
import {createBrowserRouter} from 'react-router-dom'
import App from '../App'
import Home from '../pages/Home'
import About from '../pages/About'
import NotFound from '../pages/NotFound' //404页面
const router = createBrowserRouter(
[
{
path: '/',
element: <App/>,
children: [{
path: 'home',
element: <Home/>,
}, {
path: 'about',
element: <About/>,
}],
},
{
path: '*',
element: <NotFound/>,
},
],
)
export default router
index.js
将 router 应用至全局:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import router from './router'
import {RouterProvider} from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}> //全局状态管理
<RouterProvider router={router}></RouterProvider> //router应用至全局
</Provider>
</React.StrictMode>
);
App页面 重定向页面 path = ‘/home’
Navigate 不能在class类型中使用
import React from 'react'
import {Navigate, Outlet} from 'react-router-dom'
function App() {
return (
<div className="App">
<div >
//当前页面重定向到home页面
<Routes>
<Route path={'/'} element={<Navigate replace to="/home" />} />
</Routes>
//二级页面展示位置
<Outlet></Outlet>
</div>
</div>)
}