React Router :在路由更改时滚动到顶部和解析查询字符串参数

在使用 React Router 进行导航和路由时,可以使用useLocation来获取表示当前 URL 的位置对象。获得位置对象后,可以检索并解析查询字符串,如下所示:

const location = useLocation();
 const queryString = location.search;

 const params = new URLSearchParams(queryString);
 console.log(params.get('key'));

useLocation

在此之前我们先来详细了解一下useLocationuseLocation是一个返回包含当前 URL 信息的位置对象的函数。每当 URL 发生变化时,都会返回一个新的位置对象。位置对象属性:

  • hash: 锚点部分 (#)
  • pathname: 路径名
  • search: 查询字符串部分
  • state:状态
  • key

当你想要根据 URL 的更改触发函数时,可以使用useLocation,一般情况下,它与React提供的useEffect hook结合使用,比如下面的例子,我们可以使用useLocationuseEffect实现一个在路由更改时滚动到顶部的效果:

我们的示例项目有 2 个路由,“/”(HomePage)和“/about”(AboutPage)。每个页面都很长并且有一个链接组件,因此我们可以导航到另一个页面。

  • 创建一个包装组件来处理滚动恢复:
// src/pages/ScrollToTop.tsx
import { useEffect } from "react";
import { useLocation } from "react-router";

const ScrollToTop = (props) => {
  const location = useLocation();
  useEffect(() => {
    window.scrollTo(00);
  }, [location]);

  return <>{props.children}</>
};

export default ScrollToTop;
import {Link, Route, Routes, useLocation} from "react-router-dom";
import ScrollToTop from "./pages/ScrollToTop.tsx";

function App({
  return (
    <ScrollToTop>
        <Routes>
            <Route path="/" element={<HomePage />}>Home</Route>
            <Route path="/about" element={<AboutPage />}>About</Route>
        </Routes>
    </ScrollToTop>

  )
}

const HomePage = () =>{

    return <div style={{ margin: "auto", width: "80%" }}>
        <h1>Product Page</h1>
        <div style={{ backgroundColor: "green", height: 700 }}></div>
        <div style={{ backgroundColor: "grey", height: 700 }}></div>
        <div style={{ backgroundColor: "blueviolet", height: 700 }}></div>
        <Link to="/about">
            <h2>Go To About Page</h2>
        </Link>
    </div>

}
const AboutPage = () =>{

    return <div style={{ margin: "auto", width: "80%" }}>
        <h1>About Page</h1>
        <div style={{ backgroundColor: "pink", height: 700 }}></div>
        <div style={{ backgroundColor: "orange", height: 700 }}></div>
        <div style={{ backgroundColor: "purple", height: 700 }}></div>
        <Link to="/">
            <h2>Go To Home Page</h2>
        </Link>
    </div>

}

export default App

解析查询字符串参数实例

如下面的例子:

import {Route, Routes, useLocation} from "react-router-dom";

function App({
  return (
    <div style={{  height: 'calc(100vh - 40px)', padding: '20px' }}>
        <Routes>
            <Route path="/" element={<HomePage />}>Home</Route>
        </Routes>
    </div>

  )
}

const HomePage = () =>{
    const location = useLocation();
    const search = location.search;
    console.log(search);
    const params = new URLSearchParams(search);
    console.log(params.get('s'));
    return <div>
        <h3>S: {params.get('s')}</h3>
        <h3>Page: {params.get('page')}</h3>
        <h3>Limit: {params.get('limit')}</h3>
        <h3>Sort: {params.get('sort')}</h3>
        <h3>Order: {params.get('order')}</h3>
    </div>

}

export default App

测试:比如我们有这么一个链接:http://localhost:3000/?s=hello&page=23&limit=3&sort=dete&order=desc

React Router :在路由更改时滚动到顶部和解析查询字符串参数
image.png

以上就是今日分享的文章,晚安啦!!


原文始发于微信公众号(大前端编程教学):React Router :在路由更改时滚动到顶部和解析查询字符串参数

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/224004.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!