【发布时间】: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
我可能太牵强了,超出了范围,但我很想弄清楚这一点......
【问题讨论】:
-
这能回答你的问题吗? Detect Route Change with react-router
标签: javascript reactjs react-router react-hooks