【问题标题】:React how to detect route change methodReact 如何检测路由变化的方法
【发布时间】:2019-11-27 15:28:37
【问题描述】:

我的 React 应用程序中只有一个路由器,我想在每个页面上都有一个组件,并且在该组件中我想检测 url 正在更改并根据该路由更改一些类。我有一个问题,当我通过 NavLink 更改 url 时,我的方法没有被调用,我需要刷新以模拟 componentDidMount 生命周期方法。

class App extends React.Component {
  render() {
    return (
      <div>
        <BannerTop />

        <h1>Lorem ipsum</h1>
        <Navigation />
        <Switch>
          <Route path='/o-nas' strict exact component={AboutUs} />
          <Route path='/' strict exact component={Home} />
          <Redirect to='/' />
        </Switch>
      </div>
    );
  }
}

在这个横幅中我想换班

class BannerTop extends Component {
  state = {};
  render() {
    return (
      <section className={this.changeClass()} id='banner-top'>
        <div className='container'> Lorem </div>
      </section>
    );
  }

  changeClass = () => {
    console.log(this.props.location);
    return window.location.pathname === '/' ? 'home' : 'other';
  };
}

【问题讨论】:

    标签: javascript html reactjs react-router


    【解决方案1】:

    您可以为此使用withRouter HOC。

    例子:

    import { withRouter } from "react-router";
    
    class BannerTop extends Component {
      ...
    
      changeClass = () => {
        const { match, location, history } = this.props;
        console.log(location);
        return location.pathname === '/' ? 'home' : 'other';
      };
    }
    
    export default withRouter(BannerTop);
    

    您的BannerTop 组件现在已自动改进,可接收您需要的所有路由内容。

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 2016-04-12
      • 2017-12-27
      • 2018-12-29
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 2017-02-18
      • 2021-06-16
      相关资源
      最近更新 更多