簡體   English   中英

在FlatList React-native中獲取Promise作為返回值

[英]Getting Promise as return value inside FlatList React-native

使用react-native FlatList顯示值,例如:

<FlatList 
          data={this.state.oldLocations}
          showsVerticalScrollIndicator={false}
          keyExtractor={item => item.id}
          renderItem={({item,index}) =>
        <View key={index} style={styles.flatview}>
            <GoogleStaticMap
                latitude={item.latitude.toString()}
                longitude={item.longitude.toString()}
                zoom={13}
                size={{ width: 450 , height: 250 }}
                apiKey={'MY_API_KEY'}
            />

            <Text style={styles.name}>{item.id}</Text>
            <Text style={styles.email}>{item.latitude}</Text>
            <Text style={styles.email}>{item.longitude}</Text>
            {<Text style={styles.email}>{this.getAddress(item.latitude, item.longitude)})}</Text>}
          </View>

        }


        />

我的函數getAddress在FlatList返回諾言。 如何顯示返回值? 我的功能:

getAddress(lat, lng){

 return Geocoder.geocodePosition({lat: lat, lng: lng}).then(res => {
      // res is an Array of geocoding object (see below)
      console.log(res);
      return res[0].formattedAddress;
  })
  .catch(err => console.log(err))


}

異步調用不能作為渲染的一部分返回並渲染。 相反,您需要在渲染外部執行異步加載,然后將獲取的數據設置為渲染狀態。

對於您的情況,您將需要有一個用於FlatList每個項目的有狀態組件。 該組件將處理加載並在加載后顯示結果。

例如:

class MapListItem extends React.Component {
  state = {
    address: '',
  }

  componentDidMount() {
    const {
      item,
    } = this.props;

    this.getAddress(item.latitude, item.longitude);
  }

  getAddress = (lat, lng) => {
    Geocoder.geocodePosition({lat: lat, lng: lng}).then(res => {
      this.setState({
        address: res[0].formattedAddress,
      });
    });
  }

  render() {
    return (
      // All your map/details - the other parts of your current renderItem
      ...
      <Text>{this.state.address}</Text>
      ...
    )
  }
}

然后,您的FlatList renderItem變為:

renderItem={({ item, index }) => (
   <MapListItem item={item} index={index} />
)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM