微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在javascript中使用来自其他常量的变量?

如何解决如何在javascript中使用来自其他常量的变量?

我正在构建一个应用程序,用于获取用户的位置并将纬度和经度存储在变量中。我使用这些变量通过谷歌 API 获取用户的县、州/省和国家。我在 index.ts 文件中有这个,所以我可以在其他文件中使用这些 consts。我正在使用 useState 将值存储到变量中。

首先,我想询问用户他们的位置。基于此,它应该使用 stateNamecountryNamecountyName 将它们显示在单独文件中的卡片上。我怎样才能用这个项目结构做到这一点?以及如何在这些卡片文件中使用这些变量?

index.ts

export const getLocation = () => {  
  

  var [stateName,setstateName] = useState(String);
  var [countyName,setCountyName] = useState(null);
  var [countryName,setCountryName] = useState(null);
  var [stateNameshort,setstateNameshort] = useState(String);
  var [countryNameshort,setCountryNameshort] = useState(String);



  const [latitude,setlatitude] = useState(Number);
  const [longitude,setlongitude] = useState(Number);

  const [location,setLocation] = useState(Object);
  const [errorMsg,setErrorMsg] = useState(String);
    
  useEffect(() => {
        (async () => {
          if (Platform.OS === "android" && !Constants.isDevice) {
            setErrorMsg(
              "Oops,this will not work on Snack in an Android emulator. Try it on your device!"
            );
            return;
          }
          let { status } = await Location.requestPermissionsAsync();
          if (status !== "granted") {
            setErrorMsg("Permission to access location was denied");
            return;
          }
    
          let location = await Location.getCurrentPositionAsync({});
          setLocation(location);
    
          const latitude = location.coords.latitude;
          setlatitude(latitude);
          const longitude = location.coords.longitude;
          setlongitude(longitude);
        })();
      },[]);
    
      let text = "Waiting..";
      if (errorMsg) {
        text = errorMsg;
      } else if (location) {
        text = JSON.stringify(location);
      }
    


  

  useEffect(() => {
    fetchLocationData();
    return () => {};
  },[]);

  const fetchLocationData = () => {
    async () => {
      fetch(
        "https://maps.googleapis.com/maps/api/geocode/json?address=" +
          latitude +
          "," +
          longitude +
          "&key=" +
          apiKey
      )
        .then((response) => response.json())
        .then((responseJson) => {
          const resstate = responseJson.results[0].address_components.filter(
            (x: any) =>
              x.types.filter((t: Object) => t == "administrative_area_level_1")
                .length > 0
          )[0].long_name;
          setstateName(resstate);
          const resCounty = responseJson.results[0].address_components.filter(
            (x: any) =>
              x.types.filter((t: Object) => t == "administrative_area_level_2")
                .length > 0
          )[0].long_name;
          setCountyName(resCounty);
          const resCountry = responseJson.results[0].address_components.filter(
            (x: any) => x.types.filter((t: Object) => t == "country").length > 0
          )[0].long_name;
          setCountryName(resCountry);
          const resstateShort = responseJson.results[0].address_components.filter(
            (x: any) =>
              x.types.filter((t: Object) => t == "administrative_area_level_1")
                .length > 0
          )[0].short_name;
          setstateNameshort(resstateShort);
          const resCountryShort = responseJson.results[0].address_components.filter(
            (x: any) => x.types.filter((t: Object) => t == "country").length > 0
          )[0].short_name;
          setCountryNameshort(resCountryShort);
          if (countryNameshort === "US") {
            countryNameshort = "US" + "A";
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
  };
}

例如,我想使用 countryName 并将其显示Text 组件中。我该怎么做?

CountryCard.tsx

const CountriesCard = () => {
 return (
    <RectButton >
      <Text>{//countryName??}</Text>
    </RectButton>
  );
};

CountyCard.tsx

const CountiesCard = () => {
 return (
    <RectButton >
      <Text>{//countyName??}</Text>
    </RectButton>
  );
};

StateCard.tsx

const StateCard = () => {
 return (
    <RectButton >
      <Text>{//stateName??}</Text>
    </RectButton>
  );
};

解决方法

您需要返回所有要访问的值。首先,将 getLocation 重命名为 useLocation 并将代码移动到一个单独的文件中,如 use-location.ts,然后在此钩子的末尾添加一个 return 语句,如 return { countryName,countyName,stateName };。从父组件调用 useLocation(将呈现 CountriesCardCountiesCardStateCard 等)。并向它们传递所需的值。

const ParentComponent = () => {
    const { countryName,stateName } = useLocation();

    return (
        <>
            <CountriesCard countryName={countryName} />
            <CountiesCard countyName={countyName} />
            <StateCard stateName ={stateName } />
        </>
    );

}

并且在您的子组件中访问值作为道具。示例:

const CountriesCard = (props) => {
    return (
        <RectButton >
            <Text>{props.countryName}</Text>
        </RectButton>
    );
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。