react-dom.development.js:22949 Uncaught Error: Maximum update depth exceeded. This can happen when a

2 篇文章 0 订阅
2 篇文章 0 订阅

导语:


背景:编写前端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>
        )
    }
}

二、情形二

看到很多同学的解决方案是在onChangeonClickonConfirmonPressEnter等事件的处理函数,直接onClick={this.onBtnClick()},然后解决方案是onClick={() => {this.onBtnClick()}}
可以参考以下文章:
react Maximum update depth exceeded. This can happen when a component repeatedly calls…
react报Maximum update depth exceeded

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值