条件渲染取决于 URL

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;

P.S.: 我不想用 display:noneopacity: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);