学习React视频的时候遇到教程使用老版导致路由的跳转和返回都和新版不一样而报错,找了很久资料发现可以这样使用而不是使用原来的props.history.go(-1)和this.props.history.push('/home')
import React from 'react';
import {createRoot} from 'react-dom/client';
import {BrowserRouter as Router, Route, Link, Routes, useNavigate} from 'react-router-dom'
const Login=()=>{
const navigate = useNavigate();
return (
<div>
<p>登录页面</p>
<button onClick={()=> navigate('/home')}>登录</button>
</div>
)
}
const Home=()=>{
const navigate = useNavigate();
const handleBack =()=>{
navigate(-1)
}
return (
<div>
<p>我是主页</p>
<button onClick={handleBack}>返回登录页面按钮</button>
</div>
)
}
const App = () => (
<Router>
<div>
<h1>React路由基础</h1>
{/* 指定路由入口,点击哪里跳转*/}
<Link to="/login">去登陆</Link>
{/* 指定路由出口,跳转到哪里去*/}
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/login" element={<Login />}/>
</Routes>
</div>
</Router>
)
createRoot(document.getElementById('root')).render(<App/>)