edit: I completely rewrote the body of this question to better reflect what I asking
我试图弄清楚如何在调用render()之前确保我的组件状态已更改其值 .
The workflow:
我有一个组件,它是一个带有图标的简单项目 . 单击该项目时,我会更改状态,并希望通过更改背景颜色来反映UI中的更改 .
问题是,当点击图标时,我的handleClick会很好,我会执行SetState,后者又调用render() - 但是当我检查状态值时,它仍然具有旧值 . 我知道SetState是一个异步操作 - 所以我们如何解决这个简单的情况,即改变组件在其上触发的事件的显示?
Code:
class Item extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
componentWillMount() {
this.state = {
complete: this.props.complete,
};
}
handleClick(e) {
if (e === "completed") {
this.setState({ complete: !this.state.complete });
}
}
render() {
var divId = "d_" + this.props.s;
var boxClass = CssMap.forComplete(this.state.complete); //still shows old value!
return (
<div className={boxClass}>
<div id={divId}>this.props.s</div>
<span>
<i className="icon ion-ios-checkmark-outline size-16" onClick={() => this.handleClick('completed') } />
</span>
</div>
);
}};
这是一个console.log示例
componentWillUpdate: complete
app.min.js:428 calling render
app.min.js:399 handleClick alert alert-danger | icon ion-ios-star-outline size-16
正如您所看到的,handleClick完成异步事件(我最近添加的)是在render()之后调用的!
1 回答
你的问题是if语句 . 如果你看到this link,那就不好了 .