简体   繁体   中英

repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

componentDidUpdate(prevProps, prevState) {
const { data } = this.state;

if (prevState.data.date !== data.date) {
  const startDate = new Date(data.date.startDate);
  const endDate = new Date(data.date.endDate);
  const countDuration = new Date(endDate - startDate).getDate();
  this.setState({
    data: {
      ...this.state.data,
      duration: countDuration,
    },
  });
}

if (prevState.data.duration !== data.duration) {
  const startDate = new Date(data.date.startDate);
  const endDate = new Date(
    startDate.setDate(startDate.getDate() + +data.duration - 1)
  );
  this.setState({
    ...this.state,
    data: {
      ...this.state.data,
      date: {
        ...this.state.data.date,
        endDate: endDate,
      },
    },
  });
}

}

But this gives me error, saying Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

It looks like you're changing the data.date and data.duration properties in the wrong place. As a result, the conditions prevState.data.date.== data.date and prevState.data.duration.== data.duration are never evaluating to true and thus the setState calls happen each time, causing an infinite loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM