首页 > 解决方案 > 超过最大更新深度 ReactJs componentDidMount

问题描述

我理解了这个错误,我的 componentDidUpdate 函数正在创建一个无限循环,我不知道如何修复它。我发现了回溯显示给我的两个错误,但我不知道该怎么做。这是提交处理程序函数,它位于主(登录)组件中:

submitHandler = event => {          
    event.preventDefault();
    const {month, day, year} = this.state.data;
    this.setState({
       loading: true,
       error: false,
       errors: {},
       data: {
          ...this.state.data,
          foundation: `${month} ${day} de ${year}`
       }
    });

    fetch('http://127.0.0.1:8000/logup/',
       {
          method: 'post',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(this.state.data)
        }).then(response => {
            this.setState({ loading: false });
            if (response.ok) {
                console.log('redirect to social nets');
            } else {
                this.setState({ error: true });
            }
            return response.json();
        }).then(json => {
            if (this.state.error) {
                this.setState({errors: json}) // The traceback give me error right here
            } else {
                console.log(json);
            }
        });    
    };

我在该登录组件的渲染中也有许多 Inputs 组件,回溯也在这里显示错误。

state = {
    error: false
};

componentDidUpdate() {
      let bad = Object.keys(this.context.errors).includes(this.props.name);
      if (bad) {
         this.setState({ error: true }); // traceback give me error too.        
      };
   };

追溯

错误

标签: javascriptreactjs

解决方案


在您componentDidUpdate以下列方式更新状态:

this.setState({ error: true })

您这样做的条件是:

Object.keys(this.context.errors).includes(this.props.name)

设置状态会导致组件重新渲染并更新,因此componentDidUpdate将再次运行。但是,当这种情况发生时,您的上述条件很可能仍然是正确的。因此,您将再次更新状态,并且 React 不会短路状态更新,因为您每次都在创建一个新对象。在这里拯救自己的一种简单方法是将您的条件更改为:

      if (bad && !this.state.error) {
         this.setState({ error: true }); // traceback give me error too.        
      };

推荐阅读