如何检测刷新页面和路由变化以做出反应?

时间:2019-06-28 12:27:51

标签: reactjs

每次更改路线或刷新页面时,我都必须调用特定功能(UserWarnings)。

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

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: } } 调用componentsHandler函数:

componentDidUpdate

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

我该如何处理?

2 个答案:

答案 0 :(得分:2)

您可以在componentsHandler中调用componentDidMount函数。

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

答案 1 :(得分:0)

刷新后,您的应用将从头开始渲染。您需要componentDidMountcomponentDidUpdate的处理程序(如果使用钩子,则只需useEffect

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


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