【问题标题】:I get error Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate我收到错误超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况
【发布时间】:2023-04-09 04:30:01
【问题描述】:

有很多类似的问题,虽然我在这里贴出来。

我收到以下错误:

未捕获的不变违规:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

请注意,我没有在页面中使用过此类功能。

选择Datepicker时出错:

constructor(props){
super(props);
this.state={
fields: {},
errors: {}
}
}
handleIssueDate(date){
       // this.state.IssueDate = moment(date).format("YYYY-MM-DD")
       debugger;
           let fields = this.state.fields;
           fields["IssueDate"] = moment(date).format("YYYY-MM-DD")
           this.setState({
               fields
           });
           let errors = this.state.errors;
           if (errors[date] != "" || errors[date] != null) {
               errors["IssueDate"] = "";
           }

      }
render(){
return (
<DatePicker name="IssueDate" onChange={this.handleIssueDate} selected={this.state.fields.IssueDate} value={this.state.fields.IssueDate}  placeholderText={"YYYY-MM-DD"}  />)
}

编辑: 我刚刚从 setState 中删除了 moment 函数。现在它工作正常。请任何人解释这个奇怪的错误/行为。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    显然你正在改变状态。

    let fields = this.state.fields; // fields still holds the reference to the state
    
    fields["IssueDate"] = moment(date).format("YYYY-MM-DD") // here happens the mutation
    
    this.setState({ // state is changed again
        fields,
    });
    
    errors["IssueDate"] = ""; // state mutation once again
    

    建议的方法:

    在状态中定义“IssueDate”字段:

    state = {
       fields: {
          IssueDate: null,
       },
       error: {
          IssueDate: null,
       },
    }
    

    然后在你的 onChange 函数中:

    this.setState(({ fields }) => ({
       fields: {
          ...fields,
          IssueDate: moment(date).format("YYYY-MM-DD"),
       },
    });
    

    犯错时做同样的事情。

    【讨论】:

    • 感谢回复,我试过了,但没用,我只是删除了 moment 功能,它运行良好。有点奇怪,你有同样的理由吗?
    • @MMJ 从 onchange 函数中删除所有内容,只需保留:this.setState({ date: date }); 并向您的状态添加一个名为“date”的新字段,删除所有其他字段。如果错误消失,则表示问题与突变有关。
    • 我刚刚从 handleIssueDate 函数中删除了时刻日期函数。它工作正常,我只是想知道为什么会抛出这种奇怪的错误消息?
    【解决方案2】:

    https://github.com/Hacker0x01/react-datepicker/blob/master/docs/datepicker.md

    selected 类型是 instanceOf(Date) 不是字符串

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 2020-12-11
      • 2019-08-12
      • 2023-03-26
      • 2018-09-13
      • 2021-04-29
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多