简体   繁体   中英

React call api when component is rendered runs twice

I have been studying react and searching and didn't find any answer for this.
So I have this component that calls my api to know what to do when it is rendered.
The problem is that it is rendered twice, and I wanted to know if that is ok because I'm telling the component to update itself or if I'm doing something wrong.
From what I've searched I see that the render runs if the setState is called, but I still find this a bit odd, maybe it's because I'm new to React but I would like to clear things out.

Example:

class Car extends React.Component {
  constructor() {
    super();
    this.state = {
      color:'none',
    };
  }

  componentDidMount(){
    this.updateColor();
  }

  updateColor() {
    this.setState(() => {
      return { color: 'red'}
    });
  }

  render() {
    console.log("potatoes");
    return (
      <div>        
        <h1>Car color: {this.state.color}</h1>
      </div>
    );
  }
}

React.render(<Car />, document.getElementById('app'));

Codepen link:
https://codepen.io/jorgemdss/pen/qBEqroE?editors=0010

If you open dev tools you see that "potatoes" are logged twice.
Is it completely normal or am I doing something wrong ?

That is completly normal.

The first render is when the component mounts and the second one is when it runs componentDidMount and calls updateColor which updates the state and render it again.

You probably don't see but your component will render none and after red .

It is normal as in first render it renders with value as 'none' and on the second render it renders with value as 'red'.

You will see that the component renders only once if you comment out setState .

When you run this code you will see the log as follows.

class Car extends React.Component {
  constructor() {
    super();
    this.state = {
      color:'none',
    };
  }

  componentDidMount(){
    this.updateColor();
  }

  updateColor() {
    this.setState(() => {
      return { color: 'red'}
    });
  }

  render() {
    console.log(this.state.color); //change potatoes to this.state.color
    return (
      <div>        
        <h1>Car color: {this.state.color}</h1>
      </div>
    );
  }
}

React.render(<Car />, document.getElementById('app'));

Console.log

"none"
"red"

I'm not that in to React, but after testing with your codepen, i think it is: The first time the Code is executed is because the React.render(<Car />, document.getElementById('app')); Then after the State changes, the Page renders again automatically.

You can test this if you add this.state.color to the console.log and/ or commentOut the setState

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