【问题标题】:How to use variables from other consts in javascript?如何在javascript中使用来自其他常量的变量?
【发布时间】:2021-07-29 01:47:43
【问题描述】:

我正在构建一个应用程序来获取用户的位置并将纬度和经度存储在变量中。我使用这些变量通过 google 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 的自定义挂钩。您可能希望创建一个调用钩子的容器/应用程序组件,然后让钩子返回您感兴趣的任何值。然后您将这些值作为道具传递给相关的子项。有意义吗?
  • 一点。你能在答案中举个例子吗?

标签: typescript react-native scope react-hooks constants


【解决方案1】:

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

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

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

}

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

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

【讨论】:

  • 谢谢。我在哪里调用父组件?
  • 取决于你的应用的目录结构,但如果你只是学习,那么可能只是把它放在App.tsx或index.ts中。不过,我不太确定您所说的“调用”父组件是什么意思。
  • 我的意思是父组件现在没有被使用,那我应该在哪里使用呢?
  • 如果你使用create-react-app创建项目,那么你可以在App.tsx使用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2021-12-17
相关资源
最近更新 更多