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(); // 執行解綁
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM