Skip to main content

redirect

路由跳转和传参

主页面

main.jsx
import { HashRouter, Link, Route, Switch } from "react-router-dom"
import styled from "styled-components"
import From from "./from"
import To from "./to"
const NavBox = styled.nav`
a {
margin: 20px 10px;
}
`

export default function Main() {
return (
<HashRouter>
<NavBox>
<Link to="/from">from component</Link>
<Link to="/to">to component</Link>
</NavBox>
<div>
<Switch>
<Route path="/from" component={From} />
<Route exact path="/to" component={To} />
{/* 路径传参:?代表可选 */}
<Route exact path="/to/:param0/:param1?" component={To} />
</Switch>
</div>
</HashRouter>
)
}

路由跳转发起

from.jsx
import { Link, useHistory } from "react-router-dom"
export default function From() {
let history = useHistory()

return (
<>
<h1>From Component</h1>
<Link
to={{
pathname: "/to",
search: "param=x", // 参数
state: {}
}}
>
Link跳转-可回退
</Link>

<br />

<Link
to={{
pathname: "/to",
search: "param=x", // 参数
state: {}
}}
replace
>
Link跳转-repalce不可回退
</Link>

<br />

<button
onClick={() => {
history.push("/to?param0=x&param1=y")
}}
>
编程式跳转-问号传参
</button>

<br />

<button
onClick={() => {
history.push({
pathname: "/to",
search: "param0=1&param1=2"
})
}}
>
编程式跳转-search传参(出现在url上,长度限制2K等问题)
</button>

<br />
<button
onClick={() => {
history.push(`/to/x/y`)
}}
>
编程式跳转-路由路径传参
</button>

<br />
<button
onClick={() => {
history.push({
pathname: "/to",
state: {
param0: "x",
param1: "y"
}
})
}}
>
编程式跳转-hide方式传参
</button>
</>
)
}

路由参数接收

to.jsx
import { useLocation, useRouteMatch } from "react-router-dom"
export default function To() {
let param0, param1

// 使用url传值,获取方式
let location = useLocation()
if (location.search) {
let usp = new URLSearchParams(location.search)
param0 = usp.get("param0")
param1 = usp.get("param1")
}

// 使用路由路径传递参数,获取方式
let match = useRouteMatch()
if (match.params && Object.keys(match.params).length > 0) {
param0 = match.params.param0
param1 = match.params.param1
}

// hide方式传参,获取方式,但是刷新参数丢失
let { state } = location
if (state) {
// console.log("state=", state)
param0 = state.param0
param1 = state.param1
}

return (
<>
<h1>To Component</h1>
<div>param0={param0}</div>
<div>param1={param1}</div>
</>
)
}