React Native UseEffect 功能未按顺序工作

时间:2021-04-29 05:47:35

标签: react-native

我想获取用户的当前位置并将其设置为 AsyncStorage 数组。我将在 useEffect 钩子中进行。但问题是我的功能无法按照给定的顺序工作。这是我的代码

useEffect(() => {
    getUserLocation();
    setUserLocation();
    check();
  }, []);

  /*Get User's Currunt Location*/

  const getUserLocation = () => {
    GetLocation.getCurrentPosition({
      enableHighAccuracy: true,
      timeout: 15000,
    })
      .then((location) => {
        var lt = location.latitude;
        var lg = location.longitude;
        setlatitude(lt);
        setlongitude(lg);
        console.log("getUserLocation", lt, lg);
      })
      .catch((error) => {
        const { code, message } = error;
        console.warn(code, message);
      });
  };

  /*Set User's Currunt Location to AsyncStorage*/

  const setUserLocation = async () => {
    try {
      await AsyncStorage.setItem("user_location", JSON.stringify(userLocation));
      console.log("setUserLocation", userLocation);
    } catch (error) {
      console.log("error setting user location");
    }
  };

  const check = () => {
    AsyncStorage.getItem("user_location", (err, result) => {
      if (result !== null) {
        console.log("check", result);
        setlatitude(result.latitude);
        setlongitude(result.longitude);
      } else {
        console.log("Data Not Found");
      }
    });
  };

1 个答案:

答案 0 :(得分:1)

每当您使用 .then 时,您都在安排您的代码在将来的某个时间点运行,当承诺完成时。所以 setUserLocationthengetUserLocation 之前运行。

另外,看起来你的 getUserLocation 设置了反应状态,直到下一次渲染才可用。我们使用效果来管理这一点。

// Get the location on mount
useEffect(getUserLocation, []);

// Whenever the location updates, set it into storage
useEffect(() => setUserLocation().then(check), [latitude, longitude]);