[英]Conditional rendering depending on URL
我的应用中有一个背景视频,它默认加载。 但我希望它不要加载到特定页面中。 这是我不工作的解决方案。 它仅在我刷新页面时才有效,当然,这不是我想要的
import React, { useEffect, useState } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import { routes } from './routes.js';
import './assets/css/style.css';
import Header from './components/global/Header';
import BgVideo from './components/global/BgVideo';
import Menu from './components/global/menu/Menu';
const App = () => {
return (
<div className='app-wrapper'>
{window.location.pathname !== '/portfolio' && <BgVideo />}
<Header />
<Menu />
<Switch>
{
routes.map(item => <Route key={item.id} path={item.pathname} exact component={item.component} />)
}
<Redirect to='/not-found' />
</Switch>
</div>
);
};
export default App;
PS:我不想用display:none
, opacity:0
或类似的东西隐藏它。 相反,我希望它根本不加载。
您必须改用路由器的位置。 这是因为 React 不知道您更改了组件中的某些内容,因此甚至不会尝试重新渲染它。
const App = (props) => {
return (
<div className='app-wrapper'>
{props.location.pathname !== '/portfolio' && <BgVideo />}
<Header />
<Menu />
<Switch>
{
routes.map(item => <Route key={item.id} path={item.pathname} exact component={item.component} />)
}
<Redirect to='/not-found' />
</Switch>
</div>
);
};
export default withRouter(App);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.