Projects often need to get current path parameters, jumps, etc., so these four apis are not trivialCopy the code
- useHistory
- useLocation
- useParams
- useRouteMatch
UseHistory can be used to jump to pages
import { useHistory } from "react-router-dom";
function HomeButton() {
let jumpAble = false;
let history = useHistory();
function handleClick() {
if(jumpAble){
// Very useful conditional jump
history.push("/home"); }}return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
Copy the code
UseLocation Obtains the current path information
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import {
useLocation
} from "react-router-dom";
function usePageViews() {
// Get the current path
const {pathname} = useLocation();
useEffect(() = > {
console.log(pathname);
}, [pathname]);
return(
<h1>test<h1>
)
}
export default React.memo(usePageViews);
Copy the code
UseParams gets the current parameter
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import {
useParams
} from "react-router-dom";
function usePageViews() {
// Get the current parameter
let { slug } = useParams();
useEffect(() = > {
console.log(slug);
}, [slug]);
return(
return <div>Now showing post {slug}</div>;) }export default React.memo(usePageViews);
Copy the code
useRouteMatch
To make the code look more organized, use this hook function to match the route closest to the route tree
mport { Route } from "react-router-dom";
function BlogPost() {
return (
<Route
path="/blog/:slug"
render={({ match}) = > {
// Do whatever you want with the match...
return <div />; }} / >); You can attachimport { useRouteMatch } from "react-router-dom";
function BlogPost() {
let match = useRouteMatch("/blog/:slug");
// Do whatever you want with the match...
return <div />; } The useRouteMatch hook performs: with no arguments and returns the match object of the current object <Route> takes a parameter, which is the same as the props parameter of matchPath. It can be a string pathname (as in the example above) or an object with a matching Route receiving item, as follows:const match = useRouteMatch({
path: "/BLOG/:slug/".strict: true.sensitive: true
});
Copy the code