javascript - React中setState方法无效
怪我咯
怪我咯 2017-04-11 11:15:02
[JavaScript讨论组]

看代码

class Background extends React.Component{
    constructor(opts) {
        super(opts);
        this.initStatus();
    }
    initStatus() {
        this.state = {
            effect: false
        }
    }
    render(){
        this.initStatus();

        return 

} componentDidMount() { this.setState({effect: true}, ()=>{ console.log(this.state.effect); }) } } export { Background }

为什么没有效果,打印出来的effect值依然是false

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(4)
天蓬老师

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

巴扎黑

读官方文档:

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中吧。^_^

怪我咯

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

迷茫

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号