2017-07-12 25 views
-1

例如,一個ArticleList組件,起初沒有數據;如何爲反應組件定義正確的initialState?

的狀態,也許是這樣的:

state = { 
 
    articleList: [], 
 
    isFetching: false 
 
}

起初,我希望它渲染到無(空)。

如果我檢查isFetching是真的,然後渲染null.But它也將呈現一個加載微調器基礎上,即isFetching狀態。

如果我檢查articleList.length === 0,然後渲染爲空。但它也希望在該狀態下顯示一些用戶友好的消息庫。

那麼如果應該有一些其他屬性來確定初始渲染結果爲空?

這種情況是否有最佳實踐?

回答

0

您可以使用 this.state = {}; 初始化狀態

然後您必須按照文檔中所述使用this.setState()。

在ES6可以使用

variable === undefined 

variable === null 

檢查的變量。

0
state = { 
    articleList : [], 
    fetching: false 
} 
render() { 
    const {fetching, articleList} = this.state; 
    if(fetching) { 
     //show loader here 
     return loader; 
    } 
    if(!fetching && articleList) { 
     if(articleList.length === 0) { 
     //show message here 
     return message; 
     } 
     //render content here 
     return content; 
    } 
    return null; 
} 
相關問題