gpt4 book ai didi

javascript - 使用 React Hooks 跟踪 URL 更改

转载 作者:行者123 更新时间:2023-12-02 16:35:34 27 4
gpt4 key购买 nike

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

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;

类型错误:无法读取未定义的属性“历史记录”

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

最佳答案

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

    const history = useHistory()

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

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

关于javascript - 使用 React Hooks 跟踪 URL 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62770266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com