简体   繁体   中英

Conditional rendering after fetch in react native

How to do conditional rendering after fetch in react native?I wan't to render components after 1.Successful fetch with the responseData 2.Network request fails 3.If there is empty responseData returned from server

For now I'm displaying only the successful result.I want to display the failure case also.How do I render Text component after unsuccessful fetch.Following is my code

  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>
);
}

Create renderNetworkFailure method in which you can display whatever you want. Into render method. check your response data is available or not? I have check blank string.

render(){
const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle()
return(
 <View>
{isResponseData}
 </View>
);

I think more precisely this is how your answer would look like, and if you want to show for the network failure as well then you must keep a state variable for it also.(Im also a beginner in react-native please correct if there is anything wrong)

render(){
return(
<View>
{(this.state.err)?this.networkFailure():({this.state.res.length? this.renderArticle():this.renderNothing()})}
</View>
)
}

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.

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