如何访问此json响应对象?

杰格713

我尝试了许多不同的方式来访问“主要”。我尝试了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>
德鲁·里斯(Drew Reese)

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

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

所以访问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!!

您可以在更深的财产上使用保护措施

info.main && info.main.temp

或使用可选的链接来检查是否main存在,然后继续temp

info.main?.temp

无论哪种情况,您都可能希望提供一个后备值,例如undefinednull,等等。

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

要么

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

要么

info.main?.temp || ""

等等...

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章