阅读 960

<react-router-dom>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树的路由

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
});
复制代码
文章分类
前端
文章标签