[英]How can I change data object in Vue component depending on route and using vue-route?
[英]How can I listen to route change in my main App component, using a custom history object?
我有一个 header 出现在我网站 95% 的页面中,所以我将它安装在我的主要应用程序组件中。 对于其他 5% 的页面,尽管我需要它消失。
我想一个好方法是根据当前路线将 state 从 true 更改为 false,并且 state 将确定 header 是否安装。
起初我尝试仅使用window.location.href
作为useEffect
依赖项,但这似乎不起作用。 我已经阅读了有关收听历史记录位置的选项,但我不断收到Cannot read property 'history' of undefined
。 我认为这可能是因为我正在使用自定义历史组件,或者可能是因为我尝试在我的主 App 组件中这样做? 没有把握。
这是我的历史 object:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
我在我的Router
中使用它是这样的:
<Router history={history}>
CONDITIONAL COMPONENT
<Switch>
...routes
</Switch>
</Router>
这就是我尝试听的方式,其中history
是我的自定义历史 object const MyHistory = useHistory(history)
useEffect(() => {
return MyHistory.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[MyHistory])
您正在尝试在呈现作为 Provider 的Router
的组件中使用 useHistory。 为了使 useHistory 工作,它需要在层次结构中具有更高的路由器。
所以要么你用路由器包装 App 组件,比如
export default () => (
<Router history={history}><App /><Router>
)
或者由于您定义了自定义历史记录,您可以直接使用它而不使用 useHistory
useEffect(() => {
return history.listen((location) => {
console.log(`You changed the page to: ${location.pathname}`)
})
},[])
这就是我如何控制我的应用程序中的每一个路线变化。 我创建了一个组件来侦听useLocation给出的pathname
属性
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function AppScrollTop() {
const { pathname } = useLocation();
useEffect(() => {
console.log(`You changed the page to: ${pathname}`)
}, [pathname]);
return null;
}
然后我把组件放在<Router>
<BrowserRouter>
<AppScrollTop />
<Switch>
<Route path="/login" component={Login} />
</Switch>
</BrowserRouter>
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.