【发布时间】:2017-10-24 21:00:02
【问题描述】:
我有一个显示菜单 div 和主 div 的登录页面。此页面有两种状态
constructor(props) {
super(props);
this.state = {
file: 'Main',
menuFile: '',
}
}
我挂载我的组件并设置 menuFile 状态
componentWillMount() {
let test = 'menuMain';
this.setState({
menuFile: test
});
}
我通过从这个页面调用它们来呈现菜单和主 div
return (
<div>
<div className="menu">
<Menu handleFileChange={this.handleFileChange.bind(this)} menuFile={this.state.menuFile} handleMenuChange={this.handleMenuChange.bind(this)} />
</div>
<div className="fileDiv">
<File name={this.state.file} />
</div>
</div>
当程序加载时,所有这些都可以正常工作。问题是当我点击一个新菜单时,handleMenuChange() 被调用,但没有任何反应。
handleMenuChange() {
this.setState( {menuFile} );
}
ex.
menuFile = menuMain when the program starts.
The program loads menuMain find. When I click on a new menu, menuFile becomes the new menu name let's say...
menuFile = menuOptions
If I console log menuFile it reads 'menuOptions', but the menuOptions menu isn't rendered to screen.
If I start the program with menuFile = menuOptions - - then menuOptions is rendered out. However, if I click on a menu button, the state is updated but the new menu isn't rendered out.
状态已更新为我希望将菜单更改为的 menuFile,但该菜单仍为默认菜单。无论出于何种原因,它都没有使用新状态调用并重新呈现新菜单。
如何查看状态更新以确保重新呈现页面?
我想应该是 shouldComponentUpdate() - 但我对如何使用它感到困惑。
【问题讨论】:
-
把参数给你你的函数handleMenuChange(menuName),然后从Menu组件调用这个函数,参数像this.props.handleMenuChange('newName')。另外,如果您想要初始状态“menuMain”,为什么要将其放在 componentWillMount 中?您可以在构造函数中设置初始值并使用其他生命周期方法进行更改。
标签: reactjs components lifecycle