react的路由钩子函数主要有四种:
⭐️useHistory
⭐️useLocation
⭐️useParams
⭐️useRouteMatch
但是使用这些钩子函数React版本必须>= 16.8
useHistory
这个钩子可以访问history,可以更好的进行导航
首先声明此钩子函数
import React, {Component} from 'react';
import {useHistory} from "react-router-dom";
//引入useHistory
function ReactUseHistory() {
let history = useHistory();
function handleClick() {
history.push("/");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
export default ReactUseHistory;
使用
import React, {Component} from 'react';
import ReactUseHistory from "../reactRouter/ReactUseHistory";
class Personal extends Component {
render() {
return (
<div>
<h4>个人中心页</h4>
<ReactUseHistory />
</div>
);
}
}
export default Personal;
QQ20200812-152621.png
点击Go home按钮,即可跳转到首页。
useLocation
此钩子可以返回location表示当前URL对象
定义
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
useLocation
} from "react-router-dom";
//引入useLocation
function usePageViews() {
let location = useLocation();
// 在此可以做一些统计
// React.useEffect(() => {
// ga.send(["pageview", location.pathname]);
// }, [location]);
console.log('useLocation',location)
}
export default usePageViews
使用
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route,
useParams,
useRouteMatch
} from "react-router-dom";
import usePageViews from'./ReactUseLocation'
function BlogPost() {
let {id} = useParams();
//useLocation 引入定义useLocation直接使用即可
usePageViews()
return (
<div>
<h4>新闻详情页</h4>
<p>params:{id}</p>
</div>)
}
export default BlogPost;
QQ20200812-153723.png
QQ20200812-153750.png
当点击左侧的导航时,可以直接获取location表示的URL对象
useParams
useParams返回URL参数的键值对的对象
定义此钩子
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route,
useParams,
useRouteMatch
} from "react-router-dom";
//引入useParams
function BlogPost() {
let {id} = useParams();
return (
<div>
<h4>新闻详情页</h4>
<p>params:{id}</p>
</div>)
}
export default BlogPost;
使用
<Switch>
<Route exact path={'/news'} component={NewsDetail}>
</Route>
<Route path="/news/list/:id">
<BlogPost />
{/* 将此函数式组件导入直接使用即可 */}
</Route>
</Switch>
QQ20200812-154821.png
每次访问不同的路由,可以取出其中的params
useRouterMatch
此钩子可以精准匹配路由然后显示对应的页面
定义
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route,
useParams,
useRouteMatch
} from "react-router-dom";
import usePageViews from'./ReactUseLocation'
function BlogPost() {
let {id} = useParams();
//useLocation
usePageViews()
//useRouteMatch精准匹配params
//如果匹配不成功,则match为null,匹配成功返回路由对象
let match = useRouteMatch("/news/list/:id=3");
if (match){
return (
<div>
<p>精准匹配 新闻{id}</p>
</div>
)
}
return (
<div>
<h4>新闻详情页</h4>
<p>params:{id}</p>
</div>)
}
export default BlogPost;
使用
<Switch>
<Route exact path={'/news'} component={NewsDetail}>
</Route>
<Route path="/news/list/:id">
<BlogPost />
{/* 将此函数式组件导入直接使用即可 */}
</Route>
</Switch>
效果
QQ20200812-155259.png
只有当路由精准匹配时,才会显示对应的组件
网友评论