React delayed rendering

百般思念 提交于 2019-12-11 03:05:14

问题


Assume I have a tab control component written in React. Only the active tab will be rendered for better performance (if I render all tabs, it will take 5 seconds, because there are about 20 tabs, each containing plenty of data). Other tabs will be rendered when I click them to activate them.

This works very well except for one tab. The special tab is much bigger than others, it contains a table that has 2000 rows, so React takes 3 seconds to render it. This makes the user experience pretty bad: you click the tab, nothing happens for 3 seconds because React is busy rendering, then suddenly the big table appears.

Without React, I usually do this:

  1. Put some loading indicator in the new active tab
  2. Switch to the new active tab
  3. setTimeout(render(), 50);

Since the actual rendering happens after 50ms, browser has enough time to update UI. User will see the new active tab immediately after they click it, and there is a loading indicator in the new active tab, now waiting 3 seconds is much more acceptable.

With React, the render() method is called by React framework, is it possible to do something similar to step 3?

I know I can replace the huge table with a paginated table, so only limited number of rows will be rendered at the same time. But my question is focused on dealing with UI components that need significant time to render.


回答1:


Yes, you can achieve something like this by giving your component state.

Add getInitialState( return { loading: true }); to your component
Change your render method, depending on state, e.g. like

if (this.state.loading) {
  return ( 
    <div className='my-nice-tab-container'>
      <div className='loading-state'>Loading...</div>
    </div>)
} else {
  return (
    <div className='my-nice-tab-container'>
      <div className='full tab contents'>
        {myHugeArray.map(item => ( return
          <Item class='one-of-list-of-2000' />
        ))}
      </div>
    </div>)
}

And add componentDidMount() to your component, something like:

componentDidMount() {
  var self = this;
  setTimeout(() => {
    self.setState({loading: false}); }, 50);
}

Then your component should first render with a loading state, and after 50ms load the entire thing.



来源:https://stackoverflow.com/questions/33097064/react-delayed-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!