最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using ComponentDidMount to load data before page renders - React - Stack Overflow

programmeradmin4浏览0评论

I am using ComponentDidMount to call data from my database and render page when data is ready. However, i have noticed the speed of my application has reduced when navigating since i have to wait for the data.

This is happening when i have large data in the database i am retrieving. My question is, is there any way of optimizing this, or i just have to render page before data loads ?

Component.JS

ponentDidMount()
     {
        this.fetchAllItems();           
     } 

 fetchAllItems(){
        return this.fetchPost().then(([response,json]) => {
         console.log('here now ',response);
         console.log(localStorage.getItem('user_token'))
           if(response.status === 200)
           {   

           }
        })
     }



     fetchPost(){
        const URL = 'http://localhost:8000/api/';
        return fetch(URL, {method:'GET',headers:new Headers ({
           'Accept': 'application/json',
           'Content-Type': 'application/json',
              })})
        .then(response => Promise.all([response, response.json()]));
     }

I am using ComponentDidMount to call data from my database and render page when data is ready. However, i have noticed the speed of my application has reduced when navigating since i have to wait for the data.

This is happening when i have large data in the database i am retrieving. My question is, is there any way of optimizing this, or i just have to render page before data loads ?

Component.JS

ponentDidMount()
     {
        this.fetchAllItems();           
     } 

 fetchAllItems(){
        return this.fetchPost().then(([response,json]) => {
         console.log('here now ',response);
         console.log(localStorage.getItem('user_token'))
           if(response.status === 200)
           {   

           }
        })
     }



     fetchPost(){
        const URL = 'http://localhost:8000/api/';
        return fetch(URL, {method:'GET',headers:new Headers ({
           'Accept': 'application/json',
           'Content-Type': 'application/json',
              })})
        .then(response => Promise.all([response, response.json()]));
     }
Share Improve this question asked Jul 13, 2019 at 8:35 SwitzzSwitzz 691 gold badge3 silver badges9 bronze badges 4
  • It does not wait for your data to arrive (at least not yet), the fetch call is async – Agney Commented Jul 13, 2019 at 8:43
  • I would go with adding spinner/loading indicator for the first page load, add list of data to localStorage and on then on page refresh load data from localStorage and update state in background with some sort of line-progress bar. – Janiis Commented Jul 13, 2019 at 8:44
  • Read this hackernoon./… – Trax Commented Jul 13, 2019 at 8:53
  • reducing speed of your application can be caused by something else, this code you provided here , give me nothing much about your navigation. but you can use Next.js And fetch your data even before ComponentDidMount and use that data as props with the help of Next.js. – Amir Rezvani Commented Dec 7, 2019 at 14:25
Add a ment  | 

3 Answers 3

Reset to default 2

Try to use axios to make call to API asynchronously, after it's done, just update your response data to state. No need to wait your page is finished loading or not, react will render by following changes of state value.

import React from 'react';
import axios from 'axios';

export default class MovieList extends React.Component {
  state = {
    movies: []
  }

  ponentDidMount() {
    axios.get(`http://localhost/movies`)
      .then(res => {
        const movies = res.data;
        this.setState({ movies: movies });
      })
  }

  render() {
    const {
       movies
    } = this.state;
    return (
      <div>
          <ul>
          { movies.map(movie => <li>{movie.name}</li>)}
          </ul>
      </div>
    )
  }
}

Have you tried the shouldComponentUpdate lifecycle method? This method accepts nextProps (new or uping props) and nextState (new or uping State) parameters. You can pare your next props and state (state preferably in your case) to determine if your ponent should re-render or not. Fewer re-renders equals to better speed and optimization. that means your pages will load faster. The shouldComponentUpdate method returns a boolean to determine if a page should re-render or not. Read more here. Also, Here's an example:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: true,
      countOfClicks: 0
    };
    this.pickRandom = this.pickRandom.bind(this);
  }

  pickRandom() {
    this.setState({
      value: Math.random() > 0.5, // randomly picks true or false
      countOfClicks: this.state.countOfClicks + 1
    });
  }

  // ment out the below to re-render on every click
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.value != nextState.value;
  }

  render() {
    return (
      <div>
        shouldComponentUpdate demo 
        <p><b>{this.state.value.toString()}</b></p>
        <p>Count of clicks: <b>{this.state.countOfClicks}</b></p>
        <button onClick={this.pickRandom}>
          Click to randomly select: true or false
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

In your case all the optimization must be done in the backend.

But if there is something that can be done in React is using Should Component Update as previous ment mentioned.

发布评论

评论列表(0)

  1. 暂无评论