Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside com

最近进入了项目组,把之前的代码拉了下来,前段时间大致看了看。

上周学长让我把项目里面的一些老东西给改一改,比如一些string的ref,以及一些即将废弃的生命周期函数,例如:componentWillReceiveProps,componentWillMount等等

ref修改的很顺利,但是生命周期函数修改的很麻烦,因为一些函数componentWillReceiveProps,componentWillMount等等,是无法找到完美替代的新的生命周期函数的,新推出的getDerivedStateFromProps,是个静态方法,要使用这个,里面的内容要修改很多。

在找componentWillReceiveProps的替代函数时,最终还是选择了shouldComponentUpdate,这个函数就在componentWillReceiveProps下面一层,可以进行收到新的props后的一些修改等等,但是,在修改的过程中,却出现了一些问题

修改前:

componentWillReceiveProps(nextProps) {
   
       this.sortServiceData(nextProps.services);
    };

修改后:

 shouldComponentUpdate(nextProps){
        
        
        this.sortServiceData(nextProps.services);
        
        return true
    }

按道理来说没有什么问题,但是,控制台却进行了报错:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

大致意思就是发生了死循环,在componentWillUpdate或者componentDidUpdate中调用了setstate,我:?????我并没有调用这两个函数,仍然发生了死循环

仔细看代码,找到了问题的关键,在sortServiceData函数中,有一段这样的代码:

this.setState({
            services: services
        });

分析:

一方面,调用了setstate,那么就会调用shouldComponentUpdate,但是shouldComponentUpdate调用了sortServiceData

sortServiceData函数里面又调用了setstate,会无限循环下去

所以加上一个判断就可以了:

shouldComponentUpdate(nextProps){
        
        if(nextProps.services!==this.state.services)
            this.sortServiceData(nextProps.services);
        
        return true
    }

问题解决!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值