1

react native fetch 后如何进行条件渲染? 1.Successful fetch with the 2.Network request failed 3.If responseData there is empty responseDatafrom server 返回后我不想渲染组件

现在我只显示成功的结果。我也想显示失败的情况。如何在获取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>
);
}
4

2 回答 2

2

创建renderNetworkFailure可以显示任何内容的方法。入render法。检查您的响应数据是否可用?我检查了空白字符串。

render(){
const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle()
return(
 <View>
{isResponseData}
 </View>
);
于 2018-08-10T06:37:16.513 回答
0

我认为更准确地说,这就是您的答案的样子,如果您也想显示网络故障,那么您还必须为其保留一个状态变量。(我也是 react-native 的初学者,如果有请更正哪里不对了)

render(){
return(
<View>
{(this.state.err)?this.networkFailure():({this.state.res.length? this.renderArticle():this.renderNothing()})}
</View>
)
}
于 2018-08-10T07:22:18.407 回答