首页 > 解决方案 > 如何在获取成功响应中呈现 react-native 组件?

问题描述

我正在尝试显示带有每种属性类型的属性数量的徽章。接收到来自 API 的数据,但 Badge 组件不呈现。

countProp = (id) => {

    fetch('http://10.0.2.2:8000/api/property/' + id).then((data) => data.json())

.then((response) => {

                ```return <Badge value={response.properties.length}/>

            });
    };

此后,在此renderItem方法中调用以下函数,该函数用作数组迭代器来呈现属性类型:

 renderItem = ({item}) => {

   return(

    <View>  
    ....

    ```{this.countProp(item.id)}

    </View>

    )

  }

标签: apireact-nativefetch

解决方案


您可能会发现将其分解为单独的组件并在 componentDidMount 中进行 api 调用更容易,例如:

import React, { Component } from "react";
import { Text, View } from "react-native";

export default class Item extends Component {
  componentDidMount() {
    fetch("http://10.0.2.2:8000/api/property/" + this.props.id)
      .then(data => data.json())
      .then(response => {
        this.setState({ length: response.properties.length });
      });
  }

  render() {
    if (!this.state.length) {
      return null;
    }
    return (
      <View>
        <Badge value={this.state.length} />
      </View>
    );
  }
}

然后使用这个组件传递它的 id:

import Item from "./path/to/Item.js";

...

<Item id={ 7 } />

推荐阅读