Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在React组件内运行异步函数';使用异步等待进行渲染?_Javascript_Reactjs_React Native_Async Await - Fatal编程技术网

Javascript 如何在React组件内运行异步函数';使用异步等待进行渲染?

Javascript 如何在React组件内运行异步函数';使用异步等待进行渲染?,javascript,reactjs,react-native,async-await,Javascript,Reactjs,React Native,Async Await,每次渲染运行贴图循环时,我都试图运行函数getJarak()。我尝试了很多方法,但使用async await仍然会出错 const getJarak = async (lat, lng) => { const lats = this.state.lastLat; const lngs = this.state.lastLong; try { const response = await axios.get('https://maps.

每次渲染运行贴图循环时,我都试图运行函数
getJarak()
。我尝试了很多方法,但使用async await仍然会出错

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

返回此.state.healthCareQ.map((health,id)=>{
返回(
{
this.props.navigation.navigate('HealthcareDisSubdis',{health});
}}>
{health.hfc_name}
{health.address1}
{/*{parseFloat(health.distance/1000).toFixed(1)}KM*/}
{getJarak(health.latitude,health.longitude)}
);
})

通常,当获取数据延迟时,我们需要显示某种加载图标,一旦获取数据,我们将删除加载程序并显示数据,这样您就可以使用componentDidMount进行调用并将数据设置为状态,在渲染函数中,您可以检查数据是否存在,然后显示数据,或者可以显示数据装载机通常,当获取数据延迟时,我们需要显示某种加载图标,一旦获取数据,我们将删除加载程序并显示数据,这样您就可以使用componentDidMount进行调用并将数据设置为状态,在渲染函数中,您可以检查数据是否存在,然后显示数据,或者可以显示数据loader

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


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

getJarak函数返回解析为文本的承诺。所以你不能渲染它。在
Text
元素中放入的任何内容都必须是字符串,而不是字符串的承诺



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

欢迎使用堆栈溢出。请不要上传。它们不能被复制来重现问题,未来的读者无法搜索它们,而且它们比文本更难阅读。请以文本形式发布实际代码以创建一个。请检查您的值,您正在代码中以文本形式显示对象。这是否回答了您的问题@JigarShah,我的值(response.data.rows[0].elements[0].distance.text)为string请将错误消息的一部分以文本形式发布,以便将来的读者可以对其进行搜索欢迎使用堆栈溢出。请不要上传。它们不能被复制来重现问题,未来的读者无法搜索它们,而且它们比文本更难阅读。请以文本形式发布实际代码以创建一个。请检查您的值,您正在代码中以文本形式显示对象。这是否回答了您的问题@JigarShah,我的值(response.data.rows[0].elements[0].distance.text)为strings请将错误消息的一部分作为文本发布,以便将来的读者可以搜索它。这不是OP问题的答案,应该作为注释添加。感谢您下次记住@JigarShah这不是OP问题的答案,应该作为注释添加。感谢您下次@JigarShahis会记得,{this.state.text}将显示不同的距离值。因为我有25套lat lng。我应该将函数getJarak放在哪一行以在render中运行?我认为您不希望每次重新渲染时都触发API调用。。。根据屏幕上的其他情况,你可能会在一分钟内触发数百次或数千次。我不知道这个API调用到底在做什么,但通常情况下,如果1)用户按下按钮,2)用户键入某个内容,3)组件刚刚安装(即将其放入组件的
componentDidMount(){…}
方法或4),您会希望触发它。这应该是答案。是,使用
componentDidMount
lifecycle功能<代码>渲染生命周期函数应该是纯函数(没有副作用)。@DrewReese,我已经从componentDidMount中的后端(api)获取了数据,然后我想使用距离矩阵api来获得距离。@syafiqhuib一旦收到api调用的响应,您就可以用任何需要的方式来处理接收到的数据。但最终您将通过将状态设置为要在屏幕上显示的文本来完成。只是想检查一下,您是想只显示一个文本元素,还是想显示一个结果列表?{this.state.text}将显示不同的距离值。因为我有25套lat lng。我应该将函数getJarak放在哪一行以在render中运行?我认为您不希望每次重新渲染时都触发API调用。。。根据屏幕上的其他情况,你可能会在一分钟内触发数百次或数千次。我不知道这个API调用到底在做什么,但通常情况下,如果1)用户按下按钮,2)用户键入某个内容,3)组件刚刚安装(即,将其放在com的
componentDidMount(){…}
方法中,您会想触发它
   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>
        );
      })