简体   繁体   English

在FlatList React-native中获取Promise作为返回值

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

Showing Values using react-native FlatList like: 使用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>

        }


        />

my Function getAddress inside FlatList returning promise. 我的函数getAddress在FlatList返回诺言。 How can i show return values? 如何显示返回值? my Func: 我的功能:

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))


}

Async calls cannot be returned and rendered as part of your render. 异步调用不能作为渲染的一部分返回并渲染。 Instead, you need to perform the async loading outside of the render and then set the retrieved data in the state for rendering. 相反,您需要在渲染外部执行异步加载,然后将获取的数据设置为渲染状态。

In your case, you will need to have a stateful component that you used for each item in your FlatList . 对于您的情况,您将需要有一个用于FlatList每个项目的有状态组件。 This component will handle loading and displaying the result once it is loaded. 该组件将处理加载并在加载后显示结果。

eg: 例如:

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>
      ...
    )
  }
}

And then your FlatList renderItem becomes: 然后,您的FlatList renderItem变为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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