简体   繁体   English

React.js - 在Render中区分加载/空状态的简洁方法

[英]React.js - clean way to differentiate loading/empty states in Render

I have my component: 我有我的组件:

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

componentDidMount() {
    // 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 component, you see a flash of the "empty state" HTML, as the server hasn't yet returned any data. 当您第一次加载此组件时,您会看到“空状态”HTML的闪存,因为服务器尚未返回任何数据。

Has anyone got an approach/a React Way™ of handling whether there is actually no data vs. showing a loading state? 有没有人有一个方法/ React Way™处理是否实际上没有数据与显示加载状态?

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. 我刚刚渲染了一个空的span元素,但你可以很容易地渲染某种类型的CSS微调器以显示它的加载。

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

http://www.css-spinners.com/ http://www.css-spinners.com/

You may also want to consider what happens if your response comes 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. 我会使用(this.state.items === null)来表示您正在等待结果和一个空数组/集合(!this.state.items.length)来表示没有返回任何结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM