React进行路由跳转


React如何进行路由跳转

React路由跳转

引入包

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

App.js中配置路由信息

import React from 'react'
import Login from './views/login/Login.jsx'
import Register from './views/register/Register.jsx'
import Layout from './views/layout/Layout'
import { HashRouter, Route, Routes } from 'react-router-dom';
function App() {
  return (
    <HashRouter>
      {/* routes线路匹配容器,所有组件都要放置才这里 */}
      <Routes>
      {/* 默认登录 */}
        <Route path='/' exact element={<Login />}></Route>
        {/* 登录 */}
        <Route path='/Login' element={<Login />}></Route>
        {/* 注册 */}
        <Route path='/Register' element={<Register />}></Route>
        <Route path='/Layout' element={<Layout />}></Route>
      </Routes>
    </HashRouter>
  );
}

export default App;

点击按钮跳转

//如有引入Link
import { Link} from 'react-router-dom';
<Link to="/Register">前往注册</Link>

函数中使用

在 React Router v6 中,useHistory 已被替换为 useNavigate

//引入包
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
//调用navigate 传入路由地址即可
navigate('/Layout');


扫描二维码,在手机上阅读

推荐阅读:

React使用lazy懒加载

React父子传值

评 论