【问题标题】:Getting undefined error on accessing JSON object in react - OpenWeatherAPI在反应中访问 JSON 对象时出现未定义的错误 - OpenWeatherAPI
【发布时间】:2020-06-30 21:16:24
【问题描述】:

我正在使用 OpenWeatherMapAPI 来获取当前天气(API 密钥被隐藏)。 这个想法是获取值并将其作为道具传递以在不同的组件中呈现。 我尝试了几种方法,但无法显示响应中的值。

响应是有效的,因为我在 jsonlint 上检查过。

我收到一个未定义的错误。

const [city, setCity] = useState();
  let currentWeather;

  {
    // UseEffect to run the effect during initial render
    useEffect(() => {
      
        axios
          .get(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric")
          .then((res) => {
            currentWeather = res.data;
          });
      
      // fetch(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric");
    }, []);
  }

  const handleInputChanges = (e) => {
    setCity(e.target.value);
  };

  const resetSearchValue = () => {
    setCity("");
  };

  const fetchWeather = async (e) => {
    e.preventDefault();
    {
      {
        axios
          .get(baseUrl + city + ",IN&APPID=" + APPKey + "&units=metric")
          .then((res) => {
            currentWeather = res.data;
            console.log("weather", currentWeather);
          });
      }
    }

    resetSearchValue();
  };

  return (
    <Container className="themed-container" fluid="sm">
      <InputGroup className="search">
        <Input
          placeholder="Enter a city in India"
          value={city}
          onChange={handleInputChanges}
        />
        <InputGroupAddon addonType="append">
          <Button color="secondary" onClick={fetchWeather}>
            Check
          </Button>
        </InputGroupAddon>
        // for testing the output
        <h1>{currentWeather.sys.country}</h1>
      </InputGroup>
      //the object wil be passed as props to other component for rendering the
      result
      <FetchWeather search={currentWeather} />
    </Container>
  );
};

export default Searchbar;

OpenWeatherAPI 响应

    JSON : {"coord":{"lon":77.6,"lat":12.98},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":297.51,"feels_like":301.13,"temp_min":295.15,"temp_max":302.04,"pressure":1010,"humidity":100},"visibility":6000,"wind":{"speed":3.45,"deg":206},"clouds":{"all":75},"dt":1593102591,"sys":{"type":1,"id":9205,"country":"IN","sunrise":1593044734,"sunset":1593091128},"timezone":19800,"id":1277333,"name":"Bengaluru","cod":200}

【问题讨论】:

标签: reactjs


【解决方案1】:

您已将 currentWeather 定义为常规 javascript 变量。

  let currentWeather;

这不会触发渲染。使用“useState”将 currentWeather 声明为状态变量,您应该可以看到数据。

【讨论】:

  • 仍然,我得到了同样的错误。这次 sys 是未定义的。如果我将其定义为对象,则国家将变为未定义。
  • 您必须为对象添加相关检查。由于“sys”是一个子属性,您必须检查 currentWeather 对象是否存在,然后才显示 currentWeather.sys.*** .. 像这样 -

    {currentWeather && currentWeather.sys && currentWeather.sys.country} h1>

  • 非常感谢,它正在工作。我不明白为什么我们需要检查响应是否成功。如果有包含多个嵌套元素的大尺寸响应,则会进行大量检查。
猜你喜欢
  • 2022-07-20
  • 2015-05-09
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
相关资源
最近更新 更多