【react-router】Redirect组件
程序员文章站
2022-06-25 11:57:18
import React from "react";import { BrowserRouter as Router, Route, Link, Redirect} from "react-router-dom";export default function App() { return (
- Home<...
import React from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect
} from "react-router-dom";
export default function App() {
return (
<Router>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
<Redirect from="/" to="/home"/>
<Route path="/about"><About/></Route>
<Route path="/users"><Users/></Route>
<Route path="/home"><Home/></Route>
</Router>
);
}
function Home(){
return <h2>Home</h2>
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}
<Redirect to/>
to
属性既可以是一个字符串,也可以是一个对象。
-
to
属性是一个字符串
<Router>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
<Redirect from="/" to="/home"/>
<Route path="/about"><About/></Route>
<Route path="/users"><Users/></Route>
<Route path="/home"><Home/></Route>
</Router>
或者
<Router>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
<Route path="/about"><About/></Route>
<Route path="/users"><Users/></Route>
<Route path="/home"><Home/></Route>
<Route path="/">
<Redirect to="/home"/>
</Route>
</Router>
-
to
属性是一个对象
import React from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
useLocation
} from "react-router-dom";
export default function App() {
return (
<Router>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
<Redirect from="/"
to={{
pathname:"/home",
state:{
from:"/"
},
a:{
b:"hellow world"
}
}}/>
<Route path="/about"><About/></Route>
<Route path="/users"><Users/></Route>
<Route path="/home"><Home/></Route>
</Router>
);
}
function Home(){
const location = useLocation();
console.log(location);
return <h2>Home</h2>
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}
本文地址:https://blog.csdn.net/qzw752890913/article/details/107891953