Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Render is called twice when fetching data from a REST API

I am trying to interact with a REST API using React, and I have realized that when I fetch the data, render is called once without the data, and then again with the data.

This throws an exception when I try to process this data, but I can use an if statement to check if data is null or not. However, I am not sure if that's needed.

class App extends Component {
  state = {
    TodoList: {},
  };

  componentWillMount() {
    axios.get("http://localhost:5001/1").then((response) => {
      this.setState({
        TodoList: response.data,
      });
    });
  }

  render() {
    console.log(this.state);
    return <h1>hello </h1>;
  }
}

This is what I see in in the console: enter image description here

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

That's perfectly normal.

Your App component flow as below:

  1. Execute render method to load the component
  2. execute codes in componentDidMount
  3. Calling axios.get which is async operation
  4. Receive data from step 2, update component state by using this.setState
  5. App component detected there's an update on state, hence execute render method to load component again

Hence, you should definitely handle the case where this.state.TodoList has no data, which happened at first load

UPDATES:

component lifecycle componentWillMount is now deprecated which means you shouldn't be using it anymore. Replace it with componentDidMount instead. Functionally wise they should be no difference in your example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...