最近进入了项目组,把之前的代码拉了下来,前段时间大致看了看。
上周学长让我把项目里面的一些老东西给改一改,比如一些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
}
问题解决!