【问题标题】:Conditional rendering after fetch in react nativeReact Native 中获取后的条件渲染
【发布时间】:2019-01-17 16:56:07
【问题描述】:

react native fetch 后如何进行条件渲染?之后我不想渲染组件 1.使用responseData成功获取 2.网络请求失败 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>
);
}

【问题讨论】:

    标签: javascript reactjs react-native conditional-rendering


    【解决方案1】:

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

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

    【讨论】:

    • 如果responseData 为空,我可以再给出一个条件吗?
    • 为什么不呢?这取决于您的要求。
    • 那会怎样?你能检查一下这个const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle() :this.renderEmptyData()
    • 不,它是一个三元运算符。就像其他的一样。 ?if:else
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2021-08-21
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多