React.js component life cycle, state behavior and asynchronous nature of JavaScript

前端 未结 3 617
天命终不由人
天命终不由人 2021-01-21 14:57

I have an issue with the expected result and the actual result. Even though the fetchData() and fetchnumberOfCommits() methods are called from the

3条回答
  •  余生分开走
    2021-01-21 15:31

    The render method is called when the component is first mounted and again when your data is received and the state has changed. That's why you're seeing the render method being called twice.

    componentWillMount() was deprecated in React 16.3. You should be using componentDidMount() for fetching data and you should expect that your component will render at least once before your data is fetched, so you'll need to render either null or a loading state before the data is fetched. I provided an example of how you can check if it was loaded correctly and show a loading message.

    class App extends React.Component {
    
      constructor() {
        super();
        this.state = {
          check: true,
          repositories: [],
          commits: [],
        };
      }
    
      componentDidMount() {
        this.fetchData();
        this.fetchNumberOfCommits();
      }
    
      fetchData() { /*...*/ }
      fetchNumberOfCommits() { /*...*/ }
    
      isLoaded() {
        return this.state.respositories.length > 0;
      }
    
      render() {
        const { repositories } = this.state;
    
        if(isLoaded) {
          return repositories.map(repo => {
            return (
              
            );
          });
        }
    
        return 

    Loading repos...

    ; } }

提交回复
热议问题