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
?
巴扎黑2017-04-11 11:17:02
读官方文档:
The second parameter is an optional callback function that will be executed once
setState
is completed and the component is re-rendered.. Generally we recommend usingcomponentDidUpdate()
for such logic instead.
看看你的render方法吧。另外,把callback的逻辑放在componentDidUpdate中吧。^_^
迷茫2017-04-11 11:17:02
this.setState({effect: true}, ()=>{
console.log(this.state.effect);
})
这个方法执行结束后,effect为true,回调函数又一次触发render事件,render里有this.initStatus();所以为false