React路由四个经常使用api

项目中常常要得到当前路径参数和跳转等,因此这个4个api不可小视
复制代码
  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

useHistory 能够用来页面跳转

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>
  );
}
复制代码

useLocation 得到当前路径信息

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);
复制代码

useParams 得到当前参数

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);
复制代码

useRouteMatch

让整个代码看起来更加有序,使用这个钩子函数可让你匹配最接近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
});
复制代码
相关文章
相关标签/搜索