就就绪距离和持续时间对本机地图方向做出反应

react native maps directions onReady distance and duration

onReady 显示的距离比渲染慢时出现问题。 想在显示渲染之前显示距离和持续时间值。

const MyMapView = (props) => {
    return (
        <MapView
            style={{ flex: 1 }}
            region={props.region}
            showsUserLocation={true}
        >
            <Marker coordinate={props.region} />
            <MapViewDirections
                origin={MapOrigin}
                destination={props.region}
                apikey={API_MAP.API}
                strokeWidth={3}
                strokeColor="hotpink"
                onReady={result => {
                    MapData.distance = result.distance
                    MapData.duration = result.duration
                    console.log(`Distance: ${MapData.distance} km`)
                    console.log(`Duration: ${MapData.duration} min.`)
                }}
            />
            <Body>
                <Text>distance : {MapData.distance} km.time : {MapData.duration} min</Text>
            </Body>
        </MapView>
    )
}

显示一个值后,它会先在文本中显示该值,然后再将其存储在 const 文件中。

尝试强制更新您的组件。

class MyMapView extends React.Component {
  render() {
    return (
      <MapView
        style={{ flex: 1 }}
        region={props.region}
        showsUserLocation={true}
      >
        <Marker coordinate={props.region} />
        <MapViewDirections
          origin={MapOrigin}
          destination={props.region}
          apikey={API_MAP.API}
          strokeWidth={3}
          strokeColor="hotpink"
          onReady={result => {
            MapData.distance = result.distance
            MapData.duration = result.duration
            console.log(`Distance: ${MapData.distance} km`)
            console.log(`Duration: ${MapData.duration} min.`)
            this.forceUpdate()
          }}
        />
        <Body>
          <Text>distance : {MapData.distance} km.time : {MapData.duration} min</Text>
        </Body>
      </MapView>
    )
  }
}