简体   繁体   English

如何访问这个 json 响应对象?

[英]How can I access this json response object?

I have tried many different ways to access "main".我尝试了许多不同的方法来访问“main”。 I have tried info.main, info["main"], info["- main"], I can't figure out how to access it and I continue to get "temp" of undefined.我试过 info.main, info["main"], info["- main"],我不知道如何访问它,我继续得到未定义的“临时”。 Info.base works just fine. Info.base 工作得很好。

Here is an image of the state inside my components on google chrome.这是我在 google chrome 上的组件内部状态的图像。 https://i.stack.imgur.com/SHkU3.png

Here is what it looks like in json format这是 json 格式的样子https://i.stack.imgur.com/V0KAm.png

Why is info.main.temp not working, but info.base is?为什么 info.main.temp 不起作用,而 info.base 起作用? If i remove the h1 info.main.temp the page renders just fine, as soon as I put it back the app crashes.如果我删除 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>

Your initial state is an empty object ( {} )您的初始状态是一个空对象 ( {} )

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

so accessing base or main of that object is ok and each would initially be undefined on the first renders until state is updated, but trying to go deeper, ie info.main.temp will result in the error.因此访问该对象的basemain是可以的,并且每个对象最初在第一次渲染时都是undefined ,直到状态更新,但尝试更深入,即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!!

You can use a guard on the deeper property您可以在更深的属性上使用警卫

info.main && info.main.temp

Or use optional chaining to check if main exists before continuing on to temp或者使用可选链来检查main存在,然后再继续到temp

info.main?.temp

In either case you likely also want to provide a fallback value so undefined or null , etc.. aren't leaked out to the UI在任何一种情况下,您可能还想提供一个后备值,以便undefinednull等不会泄露到 UI

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

or或者

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

or或者

info.main?.temp || ""

etc...等等...

 const info = {}; console.log('info', info); // {} console.log('info.main.temp', info.main?.temp); // undefined console.log('info.main.temp', info.main?.temp || 'fallback'); // fallback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM