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

如何访问此json响应对象?

如何解决如何访问此json响应对象?

我尝试了许多不同的方式来访问“ main”。我已经尝试过info.main,info [“ main”],info [“-main”],但我不知道如何访问它,并且继续得到未定义的“ temp”。 Info.base可以正常工作。

这是我在谷歌浏览器组件中的状态图。

https://i.stack.imgur.com/SHkU3.png

这是json格式

https://i.stack.imgur.com/V0KAm.png

的样子

为什么info.main.temp不起作用,而info.base是为什么? 如果我删除h1 info.main.temp,则只要将其放回应用程序崩溃,页面的呈现就很好。

function Body(props) {
  const [location,setLocation] = useState({});
  const [info,setInfo] = useState({});

  function getGeo() {
    navigator.geolocation.getCurrentPosition(function (position) {
      setLocation({
        lat: position.coords.latitude,long: position.coords.longitude,});
    });
  }

  useEffect(() => {
    getGeo();
    if (location.lat === undefined || location.long === undefined) {
      return;
    }
    fetch(
      `http://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${location.long}&units=metric&appid=key`
    )
      .then((response) => {
        return response.json();
      })
      .then((result) => {
        setInfo(result);
      })
      .catch((err) => {
        console.log(err);
      });
  },[location.lat,location.long,setInfo]);
return (
    <>
      <img className="adv" src="image1.png" />
      <div className="grid-block-container">
        <div className="city-weather">
          <div className="info-container">
            <h2>{info.base} Weather</h2>
            <p>as of 10:31 pm CDT</p>
            <h1>{info.main.temp}&#176;</h1>
            <h2>Party Cloudy</h2>
            <h3>10% chance of rain through 11pm</h3>
          </div>

解决方法

您的初始状态是一个空对象({}

const [info,setInfo] = useState({});

因此可以访问该对象的basemain,并且每个对象最初在第一个渲染上都是undefined,直到状态更新,但尝试更深入,即{{1 }}将导致错误。

info.main.temp

您可以在更深的属性上使用防护措施

const info = {};

console.log('info',info); // {}
console.log('info.base',info.base); // undefined
console.log('info.main',info.main); // undefined
console.log('info.main.temp',info.main.temp); // error!!

或使用optional chaining检查info.main && info.main.temp 是否存在,然后继续进行main

temp

在任何一种情况下,您可能还希望提供一个备用值,以使info.main?.temp undefined等不会泄漏到用户界面

null

(info.main && info.main.temp) || "Loading..."

(info.main && info.main.temp) || ""

等...

info.main?.temp || ""

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