我正在使用Material-ui的选项卡,这些选项卡是受控的,并且将它们用于(React-router)链接,如下所示:
<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)
我可以通过设置状态来更改,但是当按下浏览器的后退按钮时,我不知道如何处理该事件?
我发现了这一点:
window.onpopstate = this.onBackButtonEvent;
但这在每次状态更改时都会调用(不仅在返回按钮事件发生时)
这是我最终做的事情:
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}) } } }
谢谢大家的帮助