javascript - 如何使用自定义历史对象监听主 App 组件中的路由更改?
问题描述
我有一个标题出现在我网站 95% 的页面中,所以我将它安装在我的主 App 组件中。对于其他 5% 的页面,尽管我需要它消失。
我想一个好方法是根据当前路由将状态从 true 更改为 false,并且该状态将确定标头是否安装。
起初我尝试仅将window.location.href
其用作useEffect
依赖项,但这似乎不起作用。我已经阅读了有关收听历史位置的选项,但我不断收到Cannot read property 'history' of undefined
. 我认为这可能是因为我正在使用自定义历史组件,或者可能是因为我尝试在我的主 App 组件中这样做?没有把握。
这是我的历史对象:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
我Router
像这样使用它:
<Router history={history}>
CONDITIONAL COMPONENT
<Switch>
...routes
</Switch>
</Router>
这就是我尝试听的方式,history
我的自定义历史对象在哪里 const MyHistory = useHistory(history)
useEffect(() => {
return MyHistory.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[MyHistory])
解决方案
您正在尝试在呈现提供程序的组件中使用 useHistory Router
。为了使 useHistory 工作,它需要在层次结构中具有更高的路由器。
所以要么你用路由器包装 App 组件,比如
export default () => (
<Router history={history}><App /><Router>
)
或者由于您定义了自定义历史记录,您可以直接使用它而不使用 useHistory
useEffect(() => {
return history.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[])
推荐阅读
- html - 来自外部精灵文件的 SVG
- azure-resource-manager - 创建函数应用程序并通过代码而不是容器发布时是否需要 Linuxfxversion
- python - altair_saver 在循环期间停止:WebDriverException:消息:未知错误:调用函数结果必须是字典
- r - 有没有办法直接使用链接在 RStudio 中运行保存的 bigquery?
- time-series - 如何为时间序列数据创建联合数据?
- ios - 如何从 RN 应用程序获取/设置 iOS“首选语言”?
- r - 如何编码列的前 5 个值
- php - mysql INSERT 失败但未抛出错误:max_allowed_packet:设置显示冲突结果
- oauth - 对于 CLI,此 Auth0 身份验证方法是否安全
- javascript - 事件在最小化窗口 extjs 中不起作用