呈现API状态的问题- React Native

jaql4c8m  于 2022-12-27  发布在  React
关注(0)|答案(1)|浏览(140)

我正在制作一个天气应用程序,当我获取响应时,我将其传递给一个状态,当我尝试在标记中呈现它时,我得到这个错误:“undefined不是一个对象(评估'weather.wind. speed')“,但是当响应传递给LET,我试图呈现它时,LET显示为undefined。我在REACT NATIVE上,我点击一个按钮,将我带到另一个屏幕。

import {  View } from "react-native";
import React, { useState, useEffect } from "react";
import {Text } from "react-native-elements";

export const ViewPlace = ({ route }) => {

  const [clima, setClima] = useState([]);
  let feels_like;
  let humidity;
  let temp;
  let description;
  let icon;
  let speed;
  let main;

  const apikeyWeather = "a0d96ca4ea71b0ef8a8a2d04132b3941";
  const api = `https://api.openweathermap.org/data/2.5/weather?q=${item.city}&units=metric&appid=${apikeyWeather}&lang=es`;

  useEffect(() => {
    (async () => {
      const response = await fetch(api);
      const data = await response.json();
      setClima(data);

      feels_like = data.main.feels_like;
      humidity = data.main.humidity;
      temp = data.main.temp;
      description = data.weather[0].description;
      icon = data.weather[0].icon;
      main = data.weather[0].main;
      speed = data.wind.speed;

      console.log(humidity) //OK response
   
    })();
  }, []);

 console.log(humidity) //undifined
  return (
    <>
      <View style={styles.container}>
      
  <Text>{clima.wind.speed}</Text> //undefinded is not an object(evaluating 'clima.wind.speed')
          <Text>kk</Text>

      </View>
    </>
  );
};
rggaifut

rggaifut1#

您误解了React钩子的工作原理。您实现的useEffect()钩子与componentDidMount()相似。这意味着,在调用 * useEffect()之前,您的初始render()被调用 *。因此,clima.wind.speedundefined,因为您还没有调用setClima(data);。此外,clima是一个 array,但你却把它当作一个“物体"
正确初始化状态,如果数据还在,执行一个检查。

const [clima, setClima] = useState({});
...

const _renderWindSpeed = () => {
    if(Object.keys(clima).length > 0) {
        return <Text>{clima.wind.speed}</Text>
    } else {
       return <Text>Loading...</Text>
    }
}

...
  return (
    <>
      <View style={styles.container}>
          {_renderWindSpeed()}
          <Text>kk</Text>
      </View>
    </>
  );

不用这样

let feels_like;
let humidity;
let temp;
let description;
let icon;
let speed;
let main;
...
feels_like = data.main.feels_like;
humidity = data.main.humidity;
temp = data.main.temp;
description = data.weather[0].description;
icon = data.weather[0].icon;
main = data.weather[0].mai

一句忠告。永远不要公开发布API密钥:)

相关问题