在 React-router 中拦截/处理浏览器的后退按钮? [英] Intercept/handle browser's back button in React-router?
问题描述
我正在使用 Material-ui 的选项卡,这些选项卡是受控的,我将它们用于 (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"/>} />
如果我正在访问仪表板/数据并单击浏览器的后退按钮我去(例如)仪表板/用户,但突出显示的选项卡仍保留在仪表板/数据(值 = 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屋!