与APIReact Native,错误:undefined不是对象

osh3o9ms  于 2023-01-31  发布在  React
关注(0)|答案(1)|浏览(133)

我尝试将Weather API与React Native一起使用,但出现以下错误。似乎问题是在getAdressData完成之前使用了const。在这种情况下,我如何使用const并修复此错误?
错误

undefined is not an object (evaluating 'whether.sys.sunrise')

代码

〜〜〜〜〜〜〜〜〜〜
export const AddressScreen = () => {
    const [address, setAddress] = useState('');

    const baseURL = `${APIKey}`
    
    const getAddressData = () => {
        axios.get(baseURL)
                .then((response) => {setAddress(response.data)})
                .catch(error => console.log(error))
        };
    
    const sunrise =  new Date(weather.sys.sunrise * 1000); //Error
    const sunriseTime = sunrise.toLocaleTimeString();

    return (
        <KeyboardAvoidingView>
            〜〜〜〜〜〜〜〜
            <View>
                <Text>
                       Sunrise: {(sunriseTime)}
                </Text>
            </View>
        </KeyboardAvoidingView>
    );
0g0grzrc

0g0grzrc1#

JavaScript编译器错误已清除,错误为。您正在尝试访问weather.sys.sunrise对象属性,但尚未定义/初始化。
看起来你正在尝试获取一个特定位置的天气信息。如果这是你的代码的意图的话。
重构代码如下:

export const AddressScreen = () => {
  const [address, setAddress] = useState(null);
  const baseURL = `${APIKey}`;

console.log("Fetched weather data:",address)

  const getAddressData = () => {
    axios
      .get(baseURL)
      .then((response) => {

       console.log("Server response:",response)
        setAddress(response.data);
      })
      .catch((error) => console.log(error));
  };

  useEffect(() => {
    getAddressData();
  }, []);

  // Don't access weather data until fetched and assigned to state value.
  if (!address?.sys) return null;

  const sunrise = new Date(address.sys.sunrise * 1000);
  const sunriseTime = sunrise.toLocaleTimeString();

  return (
    <KeyboardAvoidingView>
      <View>
        <Text>Sunrise: {sunriseTime}</Text>
      </View>
    </KeyboardAvoidingView>
  );
};

相关问题