导语:
背景:编写前端React
代码遇到的问题。
原因:在render
函数里,直接调用this.setState
改变state
。当state
改变时,React
会重新调用render
函数渲染组建,然后再次setState
,再次渲染。触发死循环
一、情形一
1. 看看代码
import React from 'react';
export default class MaxUpdateDepthExceeded extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render = () => {
const { count } = this.state;
console.log('count = ' + count);
this.setState({
count: count + 1,
});
return (
<div>
Maximum update depth exceeded.
</div>
)
}
}
2. 看看报错
3. 看看方案
3.1 避免在render函数里直接setState
可以尝试在constructor
里设置state
:
import React from 'react';
export default class MaxUpdateDepthExceeded extends React.Component {
constructor(props) {
super(props);
const { count } = this.props;
this.state = {
count: count || 0,
};
}
render = () => {
return (
<div>
Maximum update depth exceeded.
</div>
)
}
}
或者在生命周期函数里改变state
import { message } from 'antd';
import Axios from 'axios';
import React from 'react';
export default class MaxUpdateDepthExceeded extends React.Component {
constructor(props) {
super(props);
const { count } = this.props;
this.state = {
count: count || 0,
};
}
componentDidMount = () => {
Axios.get('/api/data')
.then(resp => {
const json = resp.data;
if (json.code !== 0) {
message.error('get data failed', 5);
return;
}
const { count } = json.data;
this.setState({ count: count });
}).catch(Object)
}
render = () => {
return (
<div>
Maximum update depth exceeded.
</div>
)
}
}
二、情形二
看到很多同学的解决方案是在onChange
,onClick
,onConfirm
,onPressEnter
等事件的处理函数,直接onClick={this.onBtnClick()}
,然后解决方案是onClick={() => {this.onBtnClick()}}
可以参考以下文章:
react Maximum update depth exceeded. This can happen when a component repeatedly calls…
react报Maximum update depth exceeded