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.
Has anyone got an approach/a React Way™ of handling whether there is actually no data vs. showing a loading state?
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>);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.