javascript - React中setState方法无效
本文介绍了javascript - React中setState方法无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
看代码
class Background extends React.Component{
constructor(opts) {
super(opts);
this.initStatus();
}
initStatus() {
this.state = {
effect: false
}
}
render(){
this.initStatus();
return <div className={cs({background: true, effect: this.state.effect})}>
<div className="background-pannel">
<div className="background-image-back"></div>
</div>
<div className="background-pannel">
<div className="background-image"></div>
</div>
</div>
}
componentDidMount() {
this.setState({effect: true}, ()=>{
console.log(this.state.effect);
})
}
}
export { Background }
为什么没有效果,打印出来的effect
值依然是false
?
解决方案
是有效果的,不过在render里面的 this.initStatus()又重新把它设置为false了
这篇关于javascript - React中setState方法无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文