我是新来的人。
为什么当状态改变时,鼠标悬停和鼠标悬停时页面无法重新呈现?如果我查看console.log
,可以看到状态的变化。但是我无法使它正常工作。这是我的代码:
export default class Nav extends React.PureComponent {
constructor(props) {
super(props);
this.navLevelOneId = '';
this.state = {
showSubMenu: []
};
}
// Mouse over function
handleHover = (id,event) => {
let showSubMenu=this.state.showSubMenu;
showSubMenu[id]=!showSubMenu[id]
this.setState({showSubMenu: showSubMenu}, () => {
console.log(this.state.showSubMenu);
});
}
render() {
return (
<div ref="megaMenu" className="navbar navbar-default navbar-static-top">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse">
<ul className="nav navbar-nav">
<li onMouseOver={this.handleHover.bind(this,0)} onMouseOut={this.handleHover.bind(this,0)}>
<a>Home</a>
</li>
<li className="dropdown menu-large" onMouseOver={this.handleHover.bind(this,1)} onMouseOut={this.handleHover.bind(this,1)}>
<a className="dropdown-toggle" data-toggle="dropdown">Product Listing</a>
<ul className={"dropdown-menu megamenu row " + this.state.showSubMenu[1]}>
<li>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
</li>
</ul>
</li>
<li className="dropdown menu-large" onMouseOver={this.handleHover.bind(this,2)} onMouseOut={this.handleHover.bind(this,2)}>
<a className="dropdown-toggle" data-toggle="dropdown">Categories</a>
<ul className={"dropdown-menu megamenu row " + this.state.showSubMenu[2]}>
<li>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
<div className="col-sm-6 col-md-3">
<a href="" className="thumbnail">
<img src="http://placehold.it/150x120" alt="test" />
</a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
);
}
}
答案 0 :(得分:2)
在使用Component
和PureComponent
之间检出the difference。
简而言之,PureComponent
对状态变化进行了比较。这意味着它只比较状态对象和数组的引用(在您的情况下,this.state.showSubMenu
是一个数组,并且引用不会更改,因此React不会在此处强制重新渲染)