useLocation
可以用来查看当前的路由,当需要匹配路由进行跳转的时候使用。
使用方式如下:
import {useLocation} from "react-router-dom";
const {pathname} = useLocation
const pathList = pathname.split('/').filter((str) => str.length > 0);
console.log("pathList", pathList);
...
我们可以看一下useLocation获得的log结果:
还有另外一种方式,不需要使用Hooks:
const {pathname} = window.location;
const pathList = pathname.split("/").filter((str) => str.length > 0);
useRouteMatch
这个Hooks可以在不使用<Route>的情况下,来实现与<Route>相同功能的路由匹配。
// before
import { Route } from 'react-router-dom'
const A = () => {
return (
<div>
<Route
path="/a1"
render={({ url }) => {
return url ? <Child match={url} /> : <Error />
}}
/>
</div>
)
}
// after
import { useRouteMatch } from 'react-router-dom'
const A = () => {
let url = useRouteMatch({
path: '/a1',
})
return (
<div>
{url ? <Child match={url} /> : <Error />}
</div>
)
}
useHistory
这个Hooks可以用来进行路由匹配的跳转:
import {useHistory} from "react-router-dom";
const history = useHistory();
history.push(`/a1/b1`);
...
还有很多的功能,比如:
`history.goBack()`------返回上一个网页
`history.listen()`-------location发生改变的时候触发的回掉
......