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

javascript - React.js - clean way to differentiate loadingempty states in Render - Stack Overflow

programmeradmin5浏览0评论

I have my ponent:

getInitialState() {
    return {
        items: []
    };
},

ponentDidMount() {
    // make remote call to fetch `items`
    this.setState({
        items: itemsFromServer
    })
},

render(){
    if(!this.state.items.length){
        // show empty state
    }
    // output items
}

Extremely contrived/sandboxed, but this is the general idea. When you first load this ponent, you see a flash of the "empty state" HTML, as the server hasn't yet returned any data.

Has anyone got an approach/a React Way™ of handling whether there is actually no data vs. showing a loading state?

I have my ponent:

getInitialState() {
    return {
        items: []
    };
},

ponentDidMount() {
    // make remote call to fetch `items`
    this.setState({
        items: itemsFromServer
    })
},

render(){
    if(!this.state.items.length){
        // show empty state
    }
    // output items
}

Extremely contrived/sandboxed, but this is the general idea. When you first load this ponent, you see a flash of the "empty state" HTML, as the server hasn't yet returned any data.

Has anyone got an approach/a React Way™ of handling whether there is actually no data vs. showing a loading state?

Share Improve this question edited Jun 22, 2015 at 23:32 benhowdle89 asked Jun 22, 2015 at 22:45 benhowdle89benhowdle89 37.5k74 gold badges207 silver badges340 bronze badges 1
  • The best way to handle this is to make your app isomorphic, that way the html is fully loaded on the page and react intelligently attaches itself. It's definitely not the simplest way though, that would be obscuring your page with a loading spinner and removing it with some JS once the DOM is ready. – nanobar Commented Jun 23, 2015 at 12:16
Add a ment  | 

1 Answer 1

Reset to default 6

I've just been rendering a empty span element but you could just as easily render a CSS spinner of some kind to show it's loading.

if(!this.state.items.length){
    return(<div class="spinner-loader">Loading…</div>);
}

http://www.css-spinners./

You may also want to consider what happens if your response es back with no results. I would use (this.state.items === null) to indicate that you are waiting for results and an empty array/collection (!this.state.items.length) to indicate that no results were returned.

发布评论

评论列表(0)

  1. 暂无评论