繁体   English   中英

在获取本机反应后进行条件渲染

[英]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.

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