使用 React Hooks 跟踪 URL 更改

shi*_*bro 2 javascript reactjs react-router react-hooks

我认为这是一个很好的问题,可以供其他人稍后参考。在我之前的修订中,我会为应用程序的每个页面或部分“硬编码”五到六个侧边栏和三到四个不同的顶部导航组件,因为我无法提出更好的解决方案来确定我当前所在的页面。

这是我找到的关于钩子的唯一资源或示例!

但根据我的应用程序的结构,我不确定如何解决这个问题。

索引.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/react-hooks';
import { apolloClient } from './utils/x';

import Router from './routes/Router';

ReactDOM.render(
  <ApolloProvider client={apolloClient}>
    <Router />
  </ApolloProvider>,
  document.getElementById('root') as HTMLElement
);
Run Code Online (Sandbox Code Playgroud)

路由器.tsx:

import React, { useEffect } from 'react';

import {
  useHistory,
  BrowserRouter,
  Route,
} from "react-router-dom";

import Landing from './landing/Landing';

import Zero from './dashboard/0';
import One from './dashboard/1';
import Two from './dashboard/2';
import Three from './dashboard/3';

const Router = () => {
    const history = useHistory()

    useEffect(() => {
        return history.listen((location) => {
            console.log(`You changed the page to: ${location.pathname}`)
        })
    },[history])

    return (
    <BrowserRouter>
      <Route exact path="/" component={Landing} />

      <Route exact path="/dashboard" component={Zero} />
      <Route exact path="/dashboard/1" component={One} />
      <Route exact path="/dashboard/2" component={Two} />
      <Route exact path="/dashboard/3" component={Three} />
    </BrowserRouter>
  );
};

export default Router;
Run Code Online (Sandbox Code Playgroud)

TypeError: Cannot read property 'history' of undefined

我可能太牵强了,超出了范围,但我很想弄清楚这一点......

shi*_*bro 5

写完最后一句话我就想,我确实超出了范围

    const history = useHistory()

    useEffect(() => {
        return history.listen((location) => {
            console.log(`You changed the page to: ${location.pathname}`)
        })
    },[history])
Run Code Online (Sandbox Code Playgroud)

以下代码运行良好,可以放入路由器中列出的组件中