单击按钮时,我正在渲染新表单 . 所以基本上我改变了组件中的状态:
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>
)
}
}
3 回答
将setTimeout调用移到
componentDidMount
内部并在其中使用this.setState
你必须使用
this.setState({newForm: true})
而不是this.state = {newForm : true}
并将
setState
放在other lifecycle stages中 .您可以在onClick结束时使用this.forceUpdate() . 参考:https://facebook.github.io/react/docs/component-api.html