[英]React not re-rendering on state change
单击按钮时,我正在渲染新表单。 所以基本上我改变了组件中的状态:
false为true或null为true
但是,奇怪的是,组件在状态更改后不会重新呈现
export default class BoardManager extends React.Component{
constructor(){
super();
this.state = {
newForm : null
};
setTimeout(() => {
this.state = {
newForm : true
};
console.log(this.state.newForm);
},1000);
}
render(){
return(
<div>
Some thing here
{this.state.newForm ? <NewBoardForm />: null}
</div>
)
}
}
非常感谢!!!
编辑!!! 解
export default class BoardManager extends React.Component{
constructor(){
super();
this.state = {
newForm : null
};
}
render(){
return(
<div>
<BoardsTable boards={BoardData.boards}/>
<button onClick={() => {
this.setState({
newForm : true
});
console.log(this.state.newForm);
}}>Add New</button>
<button onClick={() => {
this.setState({
newForm : null
});
console.log(this.state.newForm);
}}>Delete</button>
{this.state.newForm ? <NewBoardForm />: null}
</div>
)
}
}
将setTimeout调用移到componentDidMount
内部并在其中使用this.setState
你必须使用this.setState({newForm: true})
而不是this.state = {newForm : true}
并将setState
放在其他生命周期阶段 。
您可以在onClick结束时使用this.forceUpdate()。 参考: https : //facebook.github.io/react/docs/component-api.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.