【问题标题】:Tracking URL changes with React Hooks使用 React Hooks 跟踪 URL 更改
【发布时间】:2020-10-27 09:59:24
【问题描述】:

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

Here's the only resource or example I've found regarding hooks!

但是对于我的应用程序的结构,我不知道如何处理这个问题。

index.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
);

Router.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;

TypeError: Cannot read property 'history' of undefined

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

【问题讨论】:

标签: javascript reactjs react-router react-hooks


【解决方案1】:

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

    const history = useHistory()

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

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

【讨论】:

猜你喜欢
  • 2020-09-13
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多