Home  >  Q&A  >  body text

javascript - React中setState方法无效

看代码

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

怪我咯怪我咯2653 days ago412

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-11 11:17:02

    是有效果的,不过在render里面的 this.initStatus()又重新把它设置为false了

    reply
    0
  • 巴扎黑

    巴扎黑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 using componentDidUpdate() for such logic instead.

    看看你的render方法吧。另外,把callback的逻辑放在componentDidUpdate中吧。^_^

    reply
    0
  • 怪我咯

    怪我咯2017-04-11 11:17:02

    他这个是有个声明周期的问题,比较复杂,虽然上面解答了,最好自己了解一下声明周期的问题

    reply
    0
  • 迷茫

    迷茫2017-04-11 11:17:02

    this.setState({effect: true}, ()=>{

            console.log(this.state.effect);
        })

    这个方法执行结束后,effect为true,回调函数又一次触发render事件,render里有this.initStatus();所以为false

    reply
    0
  • Cancelreply