Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

React, HTML and JavaScript: Error: Maximum update depth exceeded

In my React app I am getting the following error: "Error: 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". I changed the state once the for loop is completed. I dont see what I am doing wrong. Any help will be appreciated.

//React
class Pagination extends Component {
  state = {
    li: []
  }

  liTags = (pageNum) =>{
    return(  <li className="PageNumber" key={pageNum}><span>{pageNum}</span></li>)
  }

  pagincationScript = (totalPages, page) =>{
    let li = []

    for(let i = 1; i < totalPages; i++){
      li.push(this.liTags(i))

    }
    this.setState({
      li: li
    })

    if(page > 1 && page < totalPages){
    
      return(
        <React.Fragment>
          <li className="Btn Previous"><span><i>&#8592;</i>Previous</span></li>
          {this.state.li}
          <li className="Btn Previous"><span><i>&#8594;</i>Next</span></li>
        </React.Fragment>
      )
    }
  }

  render() {
    return (
      <div className="Pagination">
        <ul>
          {this.pagincationScript(10,5)}
        </ul>
      </div>
    )
  }
}

export default PagePagination;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are basically causing a stack overflow.
You are calling a setState inside a render, but, because the setState dispatch another render, your code is causing an infinite loop.

You need to stop calling this.setState every render.
In your case, you don't need to put li inside the component's state, you can simply render {li}.

pagincationScript = (totalPages, page) => {
  let li = []

  for(let i = 1; i < totalPages; i++) {
    li.push(this.liTags(i))
  }

  if(page > 1 && page < totalPages) {

    return(
      <React.Fragment>
        <li className="Btn Previous"><span><i>&#8592;</i>Previous</span></li>
          {li}
        <li className="Btn Previous"><span><i>&#8594;</i>Next</span></li>
      </React.Fragment>
    )
  }
}

But, if you need it to be inside the state, you should move the code that populates this.state.li to a lifecycle method, like componentDidUpdate (or useEffect, if you are using hooks).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...