Reactjs 如何检测react中的刷新页面和路由更改?

Reactjs 如何检测react中的刷新页面和路由更改?,reactjs,Reactjs,每次路由更改或页面刷新时,我都必须调用特定的函数(componentsHandler) 此功能负责处理某些组件状态 componentsHandler(menuItem, event) { switch (menuItem) { case '/': this.headerTitleHandler('Search') this.searchBarHandler(true) break case '/dashboard'

每次路由更改或页面刷新时,我都必须调用特定的函数(
componentsHandler

此功能负责处理某些组件状态

componentsHandler(menuItem, event) {
    switch (menuItem) {
      case '/':
        this.headerTitleHandler('Search')
        this.searchBarHandler(true)
        break
      case '/dashboard':
        this.headerTitleHandler('Dashboard')
        break
      case '/administration':
        this.headerTitleHandler('Admin')
        this.searchBarHandler(false)
        this.searchBarInfoHandler(false)
        break
      default:          
    }
  }
因此,当路由更改时,我使用
componentdiddupdate
调用
componentsHandler
函数:

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.componentsHandler(this.props.location.pathname)
    }
  }
问题是当我刷新页面时,componentDidUpdate没有检测到它,并且没有调用
componentsHandler
函数


如何处理它?

您可以在
componentDidMount
中调用
componentsHandler
函数

  componentDidMount() {
     this.componentsHandler(this.props.location.pathname);
  }

刷新时,将从头开始渲染应用程序。您需要
componentDidMount
componentdiddupdate
的处理程序(或者如果使用钩子,只需
useffect


当你手动点击时它能工作吗?@NikhilPatil是的。如果我刷新页面,它就不工作了。你用的是旧路由器吗?对于路由是的..很抱歉没有编写它ComponentDidMount()只调用了一次!我认为它不会工作。@NikhilPatil当我们刷新或用户更改路由时,组件会在您再次访问时被销毁并重新创建。这意味着每次通过路由或刷新访问时都应该调用componentDidMount。是的,只要呈现componentDidMount()组件,就会调用componentDidMount()。我的错!
  componentDidMount() {
      this.componentsHandler(this.props.location.pathname)
  }


  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.componentsHandler(this.props.location.pathname)
    }
  }