[英]React (Native) loading component error on children
我為我的 React Native App 編寫了一個加載組件,只要未檢索到數據,它就會顯示加載屏幕。 這看起來像這樣:
function LoadingChecker({ children, data }) {
const notLoaded = data.filter((item) => !isLoaded(item));
if (notLoaded.length > 0) {
return (
<View style={[styles.infoView, styles.centered]}>
<MaterialCommunityIcons name="information-outline" color={Colors.grey} size={45} />
<Text>Loading ...</Text>
</View>
);
}
return (
{ children }
);
}
return (
<LoadingChecker data={[information]}>
<View style={styles.mainView}>
<Text>information.name</Text>
</View>
</LoadingChecker>
);
問題是我得到一個異常,表明information.name未定義。
在我看來,即使我有條件地渲染文本視圖,React 仍在准備或評估它,並且因為我的信息未定義它失敗了。 如果我將information.name替換為information?.name它可以工作,我會看到加載屏幕,然后是信息屏幕。
我做錯了什么? 我可以告訴 React 不要評估孩子嗎?
由於您沒有對LoadingChecker
中的children
做任何事情,因此我真的不明白讓LoadingChecker
封裝所有內容的意義。
我會做這樣的事情:
function Loading() {
return (
<View style={[styles.infoView, styles.centered]}>
<MaterialCommunityIcons name="information-outline" color={Colors.grey} size={45} />
<Text>Loading ...</Text>
</View>
);
}
return !isLoaded(information) ? (
<Loading />
) : (
<View style={styles.mainView}>
<Text>{information.name}</Text>
</View>
)
否則,如果您想保持當前的結構,我認為您沒有比information?.name
就像您自己建議的那樣。
在我看來,即使我有條件地渲染文本視圖,React 仍在准備或評估它,因為我的信息未定義,所以它失敗了
不,你錯了。 如果你有條件地渲染一些孩子,React 不會自行准備(盡管 React 中沒有類似的概念)它們。 為了證明這個問題,我在這里創建了一個沙箱,我在其中有條件地渲染了一個使用更新的 state 值的子組件。 只要 state 沒有更新,父組件LoadingChecker
就不會渲染其子組件, <p>Loaded done. {data.message}</p>
<p>Loaded done. {data.message}</p>
不會顯示{data.message}
的任何錯誤,而是顯示“正在加載”文本。 因此,我認為您在獲取的數據的形狀方面存在一些不同的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.