class Background extends React.Component{
constructor(opts) {
super(opts);
this.initStatus();
}
initStatus() {
this.state = {
effect: false
}
}
render(){
this.initStatus();
return <p className={cs({background: true, effect: this.state.effect})}>
<p className="background-pannel">
<p className="background-image-back"></p>
</p>
<p className="background-pannel">
<p className="background-image"></p>
</p>
</p>
}
componentDidMount() {
this.setState({effect: true}, ()=>{
console.log(this.state.effect);
})
}
}
export { Background }
为什么没有效果,打印出来的effect
值依然是false
?
是有效果的,不过在render里面的 this.initStatus()又重新把它设置为false了
读官方文档:
看看你的render方法吧。另外,把callback的逻辑放在componentDidUpdate中吧。^_^
他这个是有个声明周期的问题,比较复杂,虽然上面解答了,最好自己了解一下声明周期的问题
this.setState({effect: true}, ()=>{
这个方法执行结束后,effect为true,回调函数又一次触发render事件,render里有this.initStatus();所以为false