React的路由创建以及使用

  1. 首先router中创建index.tsx文件
  2. 在文件中编写路由
  import Home from "@/views/Home"
 import About from "@/views/About"

 import { Navigate } from "react-router-dom"

 const routes = [

   {
       path:'/',
       element:<Navigate to="/home" />
   },
   
   {
       path:'/home',
       element:<Home/>
   },
   {
       path:'/about',
       element:<About/>
   }
 ]

 export default routes
  1. 然后去main.tsx 文件中导入 文件路由表
import App from './App'

import {BrowserRouter} from "react-router-dom"

   
    
ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
.render(
  <React.StrictMode>
    {/*  */}
    <BrowserRouter>
      <App/>
    </BrowserRouter>
    
  </React.StrictMode>,
)

    
  1. 最后去App.tsx文件中
import { useState } from 'react'

import { useRoutes  } from 'react-router-dom'

import routes from './router/idnex'

function App() {
  const [count, setCount] = useState(0)
  const outlet = useRoutes(routes)
  return (
    <div className='App'>
        
       {outlet}
       
    </div>
  )
}

export default App

你可能感兴趣的:(React学习记录,react.js,javascript,ecmascript)