如何使用异步等待在React组件的渲染中运行异步函数?

时间:2020-01-03 03:49:42

标签: javascript reactjs react-native async-await

我每次渲染运行地图循环时都试图运行函数getJarak()。我已经尝试了很多方法,但是使用异步等待仍会出错。

 const getJarak = async (lat, lng) => {
      const lats = this.state.lastLat;
      const lngs = this.state.lastLong;

      try {
        const response = await axios.get('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + lats + ',' + lngs + '&destinations=' + lat + ',' + lng + '&key=APIKEY');
        console.log(response.data.rows[0].elements[0].distance.text);
        const data = response.data.rows[0].elements[0].distance.text
        return data

      } catch (error) {
        console.log("error", error);
      }
    }

   return this.state.healthCareQ.map((health, id) => {
        return (
          <TouchableOpacity key={id} activeOpacity={.6} onPress={() => {
            this.props.navigation.navigate('HealthcareDisSubdis', { health });
          }}>
            <View style={stylesLocation.health} >
              <View style={{ flex: 1, borderRadius: 14 }}>
                <Image
                  style={stylesLocation.healthImage}
                  source={health.logo === "" || health.logo === null ? require('../../asset/noimage.png') : { uri: `${health.logo}` }}
                />
              </View>

              <View style={stylesLocation.healthDetails}>
                <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
                  <Text style={{ fontSize: 14, fontWeight: 'bold', width: 230, flexWrap: 'wrap' }}>
                    {health.hfc_name}
                  </Text>
                  <Text style={{ fontSize: 12, color: '#A5A5A5', paddingTop: 5, width: 215, flexWrap: 'wrap' }}>
                    {health.address1}
                  </Text>
                </View>
              </View>
              <View style={{ flex: 0.90, justifyContent: 'center' }}>
                {/* <Text style={{ fontWeight: 'bold' }}>{parseFloat(health.distance / 1000).toFixed(1)} KM</Text> */}
                <Text style={{ fontWeight: 'bold' }}>{getJarak(health.latitude, health.longitude)}</Text>
              </View>
            </View>
          </TouchableOpacity>
        );
      })

Here my error

2 个答案:

答案 0 :(得分:1)

通常,当获取数据有延迟时,我们需要显示某种加载图标,一旦获得数据,我们将删除加载器并显示数据,因此也许您可以拥有一个componentDidMount来进行调用和设置状态和渲染功能中的数据,您可以检查数据是否存在然后显示它,否则可以显示加载器

答案 1 :(得分:1)

getJarak函数返回一个可以解析为文本的promise。所以你不能渲染它。无论您在Text元素中放入什么内容,都必须是字符串,而不是字符串的承诺。

您应该将文本保留在组件的state中,然后将其呈现在Text元素中,即<Text>{this.state.text}</Text>。然后,当您运行getJarak时,它需要使用this.setState({text: newText})更新组件的状态,而不是像当前那样返回值。