項目中常常要得到當前路徑參數和跳轉等,因此這個4個api不可小視
複製代碼
import { useHistory } from "react-router-dom";
function HomeButton() {
let jumpAble = false;
let history = useHistory();
function handleClick() {
if(jumpAble){
// 很是好用的條件跳轉
history.push("/home");
}
}
return (
<button type="button" onClick={handleClick}> Go home </button>
);
}
複製代碼
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import {
useLocation
} from "react-router-dom";
function usePageViews() {
// 得到當前路徑
const {pathname} = useLocation();
useEffect(() => {
console.log(pathname);
}, [pathname]);
return(
<h1>test<h1>
)
}
export default React.memo(usePageViews);
複製代碼
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import {
useParams
} from "react-router-dom";
function usePageViews() {
// 得到當前參數
let { slug } = useParams();
useEffect(() => {
console.log(slug);
}, [slug]);
return(
return <div>Now showing post {slug}</div>;
)
}
export default React.memo(usePageViews);
複製代碼
讓整個代碼看起來更加有序,使用這個鉤子函數可讓你匹配最接近route樹的路由javascript
mport { Route } from "react-router-dom";
function BlogPost() {
return (
<Route path="/blog/:slug" render={({ match }) => { // Do whatever you want with the match... return <div />; }} />
);
}
你能夠import { useRouteMatch } from "react-router-dom";
function BlogPost() {
let match = useRouteMatch("/blog/:slug");
// Do whatever you want with the match...
return <div />;
}
該useRouteMatch鉤子執行:
不帶參數並返回當前對象的匹配對象 <Route>
接受一個參數,該參數與matchPath的props參數相同。它能夠是字符串的路徑名(例如上面的示例),也能夠是帶有匹配的Route接受道具的對象,以下所示:
const match = useRouteMatch({
path: "/BLOG/:slug/",
strict: true,
sensitive: true
});
複製代碼