[英]Hide menu and redirect when clicking on react-router Link
For the menu of my site I am using links. 对于我网站的菜单,我正在使用链接。 When clicked on menu hamburger icon a hover over menu appears which is a checkbox.
单击菜单汉堡包图标时,将出现一个悬停在菜单上的复选框。 Now I want to hide the menu after i click a Link and go to another page.
现在,我想在单击链接并转到另一个页面后隐藏菜单。 But the menu doesnt close, the page behind the menu changes which is good.
但是菜单没有关闭,菜单后面的页面发生了变化,这很好。 I setup a function which changes the checkbox state to false but it doesn't hide the menu when a Link is clicked.
我设置了一个将复选框状态更改为false的函数,但是单击“链接”时它不会隐藏菜单。
constructor(props) {
super(props);
this.state = {
hamburger: false
};
this.turnOff= this.turnOff.bind(this);
}
turnOff = (e) => {
this.setState({hamburger:false});
}
in render() i have: 在render()中,我有:
<input name="hamburger" type="checkbox" id="menuToggle" onChange={this.handleChange} checked={this.state.hamburger} className="menu-toggle-input"></input>
<Link to="/about" onClick={this.turnOff}>About</Link>
When i click on link it loads the page on the background but the menu does not close and i get an error in console: 当我单击链接时,它将在后台加载页面,但菜单没有关闭,并且在控制台中出现错误:
Can't perform a React state update on an unmounted component.
无法在已卸载的组件上执行React状态更新。
The issue is this, 问题是这样的
<Link to="/about" onClick={this.turnOff}>About</Link>
When you click on Link
, it will not wait till any associated click handler executes, in your case onClick={this.turnOff}
. 当您单击
Link
,它不会等到任何关联的单击处理程序执行onClick={this.turnOff}
(在您的情况下为onClick={this.turnOff}
。 It will directly navigates to component with path /about
and your component unmounts
. 它将直接导航到路径为
/about
组件,并且组件将unmounts
。 After component unmounts
, your turnOff
function tries to change state which is not possible. 组件
unmounts
,您的turnOff
函数会尝试更改状态,这是不可能的。
Instead of Link
you can have simple button
(styled as link), 除了
Link
您还可以使用简单的button
(样式为链接),
<button onClick={this.turnOff}>About</button>
You can make use of Redirect
from react-router-dom
package, in callback of setState. 您可以在setState的回调中使用
react-router-dom
包中的Redirect
。
Your function should be, 您的功能应该是
turnOff = (e) => {
this.setState({hamburger:false}, () => <Redirect to="/about" />);
}
Update 更新资料
You can make use of history
object, 您可以利用
history
对象,
turnOff = (e) => {
this.setState({hamburger:false}, () => this.props.history.push('/about'));
}
You need to import withRouter
from react-router-dom
and wrap your component with same. 您需要从
react-router-dom
导入withRouter
并用相同的组件包装。
import { withRouter } from 'react-router-dom';
export default withRouter(Your_Component_name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.