我认为这将是一个很好的问题,以后可以要求其他人参考。在我以前的修订版中,我会为我的应用程序的每个页面或部分"硬编码"五到六个侧边栏和三到四个不同的顶部导航组件,因为我无法想出更好的解决方案来确定我当前所在的页面。
这是我找到的唯一关于钩子的资源或示例!
但是对于我的应用程序的结构,我不确定如何处理这个问题。
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
);
路由器.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
我可能太牵强了,超出了范围,但我很想弄清楚这一点......
我一写最后一句就想到了,我确实超出了范围
const history = useHistory()
useEffect(() => {
return history.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[history])
以下代码运行良好,可以进入路由器中列出的组件