拦截/处理React-router中的浏览器后退按钮? [英] Intercept/handle browser's back button in React-router?

查看:3180
本文介绍了拦截/处理React-router中的浏览器后退按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Material-ui的Tabs,它们受到控制,我正在使用它们(React-router)这样的链接:

I'm using Material-ui's Tabs, which are controlled and I'm using them for (React-router) Links like this:

    <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/>
    <Tab value={1} label="users" containerElement={<Link to="/dashboard/users"/>} />
  <Tab value={2} label="data" containerElement={<Link to="/dashboard/data"/>} />

如果我现在正在访问仪表板/数据,我点击浏览器的后退按钮
我去了(例如)仪表板/用户,但突出显示的Tab仍然停留在仪表板/数据上(值= 2)

If I'm currenlty visting dashboard/data and I click browser's back button I go (for example) to dashboard/users but the highlighted Tab still stays on dashboard/data (value=2)

我可以通过设置状态进行更改,但我不会知道如何在按下浏览器的后退按钮时处理事件?

I can change by setting state, but I don't know how to handle the event when the browser's back button is pressed?

我发现了这个:

window.onpopstate = this.onBackButtonEvent;

但每次更改状态时都会调用此命令(不仅仅是在后退按钮事件中)

but this is called each time state is changed (not only on back button event)

推荐答案

以下是我最终的结果:

componentDidMount() {
    this._isMounted = true;
    window.onpopstate = ()=> {
      if(this._isMounted) {
        const { hash } = location;
        if(hash.indexOf('home')>-1 && this.state.value!==0)
          this.setState({value: 0})
        if(hash.indexOf('users')>-1 && this.state.value!==1)
          this.setState({value: 1})
        if(hash.indexOf('data')>-1 && this.state.value!==2)
          this.setState({value: 2})
      }
    }
  }

感谢大家帮忙lol

这篇关于拦截/处理React-router中的浏览器后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆