从useEffect钩子获取值并显示在React的功能组件中

时间:2020-07-24 23:25:00

标签: javascript reactjs ecmascript-6

我是React的新手。试图获取页面中的位置坐标并想要显示纬度和经度,但不确定如何从getCurrentPostion钩子中调用的useEffect函数中获取值。谁能帮忙吗?

这是我代码的要点。

const getCurrentPosition = async () => {
  const {
    coords: { latitude, longitude },
  } = await Geolocation.getCurrentPosition();
  return { latitude, longitude };
};

const TestComponent = () => {
  useEffect(() => {
    getCurrentPosition().then((res) => console.log('res', res));
  });
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates ( Yet to be displayed ) </div>
      </IonContent>
    </IonPage>
  );
};

2 个答案:

答案 0 :(得分:3)

这些值应该存在于某个地方的状态中。例如:

const TestComponent = () => {
  const [coord, setCoords] = useState(null);
  useEffect(() => {
    getCurrentPosition().then((res) => {
      setCoords(res);
    }
  });
  // Now you have access too coords here
  if (!coords) return <div>Loading..<div> // handle waiting for the request
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates { coords.latitude } { coords.longitude } </div>
      </IonContent>
    </IonPage>
  );
};

答案 1 :(得分:1)

const TestComponent = () => {
 const [coordinates, setCoordinates] = 
useState({latitude:"", longitude:""});
const getCurrentPosition = async () => {
  const {
    coords: { latitude, longitude },
  } = await Geolocation.getCurrentPosition();
  setCoordinates({latitude, longitude})
};
  useEffect(() => {
    getCurrentPosition();
  });
  return (
    <IonPage>
      <IonContent>
        <div>Coordinates {coordinates.latitude}</div>
      </IonContent>
    </IonPage>
  );
};