[英]Conditional rendering after fetch in react native
怎么辦條件呈現取指令后發生反應,本土?我wan't渲染組件1.Successful與取后responseData
2.Network請求失敗3,如果沒有空responseData
從服務器返回
現在我只顯示成功的結果,我也想顯示失敗的情況,獲取失敗后如何渲染Text
組件,下面是我的代碼
onPressSubmit() {
fetch("xxxx", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
url: this.state.url
})
})
.then((response) => response.json())
.then((responseData) =>
{
this.setState({
res:responseData.message,
showLoading: false
}, () => console.log(this.state.res));
}).catch((error) => {
console.error(error);
});
}
renderArticle(){
const {title} = this.state.res;
const {image} = this.state.res;
const {text} = this.state.res;
const {id} = this.state.res;
const {author} =this.state.res;
const {html} = this.state.res;
return (
<TouchableOpacity
onPress={() => Actions.addNewarticle({heading:title, authorname:author, description:text, htmlcon:html})}
>
<CardSection>
<View style={{ flexDirection: "row" }}>
<Image
source={{ uri:image }}
style={styles.thumbnail_style}
/>
<Text style={styles.textStyle}>{title}</Text>
</View>
</CardSection>
</TouchableOpacity>
);
}
render(){
return(
<View>
{this.renderArticle()}
</View>
);
}
創建renderNetworkFailure
方法,您可以在其中顯示所需的任何內容。 進入render
方法。 檢查您的響應數據是否可用? 我檢查了空白字符串。
render(){
const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle()
return(
<View>
{isResponseData}
</View>
);
我想更確切地說,這就是您的答案的樣子,如果還要顯示網絡故障,則還必須為其保留狀態變量。(我也是react-native的初學者,如果有的話哪里不對了)
render(){
return(
<View>
{(this.state.err)?this.networkFailure():({this.state.res.length? this.renderArticle():this.renderNothing()})}
</View>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.