【问题标题】:Conditional rendering depending on URL根据 URL 进行条件渲染
【发布时间】:2021-07-10 14:41:30
【问题描述】:

我的应用中有一个背景视频,它默认加载。但我希望它不要加载到特定页面中。这是我不工作的解决方案。它仅在我刷新页面时才有效,当然,这不是我想要的

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 或类似的东西隐藏它。相反,我希望它根本不加载。

【问题讨论】:

  • 拜托,别再告诉别人你在 ReactJS 方面有很好的技能,这是基础知识,所以我猜你才刚刚开始。
  • Martin,谢谢你的回答,但是请不要再从我身上跑过去了,我什至不知道它在哪里写了我在所有方面的出色技能。

标签: javascript reactjs conditional-rendering


【解决方案1】:

您必须改用路由器的位置信息。这是因为 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);

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2011-03-15
    • 1970-01-01
    • 2020-11-07
    • 2017-03-08
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多