Stay Hungry,Stay Foolish!

React-Router 非Route监管组件如何监听location变化?

react-router-dom

https://github.com/remix-run/react-router/blob/main/docs/getting-started/tutorial.md

对于location的变化, 不论是 hashtag方式, 或者是 通过pushstate改变urlpath 的方式,

这种情况下, 只有使用 Route 方式的 引用的 组件, 才能感知 路径变化(location对象), 加载此组件。

 

复制代码
import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import App from "./App";
import Expenses from "./routes/expenses";
import Invoices from "./routes/invoices";

const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="expenses" element={<Expenses />} />
      <Route path="invoices" element={<Invoices />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);
复制代码

 

例如:

https://reactrouter.com/web/api/history/history-is-mutable

Route引用的组件 Comp 中能够在props中拿到 location 对象。

The history object is mutable. Therefore it is recommended to access the location from the render props of <Route>, not from history.location. This ensures your assumptions about React are correct in lifecycle hooks. For example:

复制代码
class Comp extends React.Component {
  componentDidUpdate(prevProps) {
    // will be true
    const locationChanged =
      this.props.location !== prevProps.location;

    // INCORRECT, will *always* be false because history is mutable.
    const locationChanged =
      this.props.history.location !== prevProps.history.location;
  }
}

<Route component={Comp} />;
复制代码

 

 

Router模式

BrowserRouter

https://reactrouter.com/web/api/BrowserRouter

A <Router> that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App />
</BrowserRouter>

 

https://javascript.ruanyifeng.com/bom/history.html#toc6

var stateObj = { foo: 'bar' };
history.pushState(stateObj, 'page 2', '2.html');

 

HashRouter

https://reactrouter.com/web/api/HashRouter

A <Router> that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

<HashRouter
  basename={optionalString}
  getUserConfirmation={optionalFunc}
  hashType={optionalString}
>
  <App />
</HashRouter>

 

https://www.cnblogs.com/xiaonian8/p/13764821.html

复制代码
componentDidMount(){
  window.addEventListener('hashchange', this.routerEvent);
}
componentWillUnmount(){
  window.removeEventListener('hashchange',this.routerEvent);
}

routerEvent = (e)=>{
  // e.target.location.hash.replace("#","")
  // 去掉#就能获取即将跳转的那个路由的url了
}
复制代码

 

问题:对于非Route引用的组件是否也能感知location变化?

 

答案是肯定的:

https://reactrouter.com/web/api/location

location数据结构:

复制代码
{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}
复制代码

 

如下四种情况, 可以使用感知location变化。

The router will provide you with a location object in a few places:

 

使用withRouter给非Route控制组件,添加location监测能力

https://reactrouter.com/web/api/withRouter

对于定义的组件, 使用withRouter对其进行包裹,生成新的组件。

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

 

复制代码
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
复制代码

 

在组件中监听 pushState 引起的路径变化

https://www.cnblogs.com/xiaonian8/p/13764821.html

react router自带的history.listen

复制代码
let UNLISTEN;
class Client extends React.Component {
  ...,
  componentDidMount(){
    // UNLISTEN变量用来接收解绑函数
    UNLISTEN = this.props.history.listen(route => { 
      console.log(route); 
    });
  }
  componentWillUnmount(){
    UNLISTEN && UNLISTEN(); // 执行解绑
  }
}
复制代码

 

posted @   lightsong  阅读(928)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2018-10-31 ini文件格式
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示