为了账号安全,请及时绑定邮箱和手机立即绑定

超过ReactJs componentDidMount 最大更新深度

超过ReactJs componentDidMount 最大更新深度

斯蒂芬大帝 2023-10-20 17:30:10
我理解这个错误,我的 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);            }        });        };我在该登录组件的渲染中也有许多输入组件,回溯也在这里显示错误。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.              };   };
查看完整描述

3 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

在您的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.        

      };


查看完整回答
反对 回复 2023-10-20
?
青春有我

TA贡献1784条经验 获得超8个赞

您应该在内部使用某种类型的条件componentDidUpdate,以免触发状态更新。就像下面这样:


componentDidUpdate(prevProps, prevState) {

      let bad = Object.keys(this.context.errors).includes(this.props.name);

      if (prevState.error !== this.state.error && bad) {

         this.setState({ error: true }); // traceback give me error too.        

      };

   };

始终比较内部的 prevState 和 currentState 值,componentDidUpdate因为在大多数情况下这个条件就足够了。


注意:开始使用之前,componentDidUpdate请参阅文档,因为它还提供了prevProps在prevState这种情况下始终有用的值。


查看完整回答
反对 回复 2023-10-20
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

改变


if (bad) {

    this.setState({ error: true }); // traceback give me error too.        

};


if (bad && !this.state.error) {

    this.setState({ error: true }); // traceback give me error too.        

};

setState在 of 内部使用componentDidUpdate将导致它重新渲染和调用componentDidUpdate。添加额外的检查将有助于停止此循环。


查看完整回答
反对 回复 2023-10-20
  • 3 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信