简体   繁体   中英

Trying to update the state using setstate inside the return in react component and getting “Maximum update depth exceeded error”?

I'm trying to update the state directly inside the return without using any of the life cycle method and am getting error like this:

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 referred to this link for the above error, but I didn't get an appropriate solution. Is it always necessary to use a function or life cycle method to update the state?

import React, { Component } from "react";

import "./App.css";

class App extends Component {
  state = {
    name: "john"
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <header className="App-header">
          {this.state.name}
          {this.setState({ name: "abc" })}
        </header>
      </div>
    );
  }
}

export default App;

I wrote the above code and am getting the error but in console the state value is getting update and printing it in many times.

  1. You have this error because setState triggers re-render of the component each time when your component renders. This causes an endless loop of updates.

    setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

  2. Yes, it is necessary to use a function or life cycle method to update the state. You must not update a state directly in a render function. You should prepare your data for rendering before render and you should update a state in lifecycle methods or in callbacks.

This is because you are using setState inside the render method. You cannot use setState inside the render method because it will cause the Component to re-render again and again. Because in react application a Component get re-rendered only if Props pass to that component or when setState is called.

So you can use componentDidMount life-cycle to set the state.

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