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.
今天用react开发微信公众号的时候,竟然发生了如下错误?好吧!记录一下,避免以后再也不范这种低级错误。。。
1.找出问题
ok,先找到发生错误的根源
2.分析问题
这里的a标签是在一个循环里面的;
可以看见(我用红色框标记)onClick方法里面的this;
这样写的话这个this对象是指当前页面的对象;
而我们在循环里面一直调用go方法,
go = (url, param) => {
const { dispatch } = this.props;
dispatch(
routerRedux.push({
pathname: url,
params: param,
})
);
};
go方法里面调用了routerRedux.push()方法
它就会一直给出很多个警告“Hash history cannot PUSH the same path; a new entry will not be added to the history stack”
还会改变this.props
而且我在页面还调用了componentDidUpdate()生命周期函数
就像下面代码块,就会报“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时,就会发生这种情况”,
好吧,看到这点就可以理解为啥前面说“低级错误”了
componentDidUpdate() {
const {data} = this.props;
this.setState({
data: data,
});
}
3.解决方式
那么如何解决呢?其实也非常简单。ok,利用es6里面的语法就ojbk了:
结束语:为什么加一个()=>就行了呢!其实就是this指向的问题。
在使用箭头函数有这么一个注意点“this对象的指向是可变的,但是在箭头函数中,它是固定的”。