【问题标题】:How can I access this json response object?如何访问此 json 响应对象?
【发布时间】:2020-09-12 03:48:44
【问题描述】:

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

这是我在谷歌浏览器上的组件内部状态的图像。

这是json格式的样子

为什么 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>

【问题讨论】:

  • 您能否在代码中显示您进行 API 调用以获取信息的位置?你有什么错误吗?
  • 显示您调用 setInfo 的位置
  • api 完全没有错误,正如您在第一张图片中看到的那样,它的设置在我的组件中状态很好,只是由于某种原因它不允许我访问 info.main。就像它只让我访问橙色的键,其他一切都是未定义的。
  • 更新了它,但如果 info.base 工作,这怎么可能是原因?

标签: arrays json reactjs object


【解决方案1】:

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

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

或者使用optional chaining 来检查main 是否存在,然后再继续temp

info.main?.temp

在任何一种情况下,您可能还希望提供一个备用值,以便 undefinednull 等不会泄露到 UI 中

(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

【讨论】:

  • 从未听说过可选链,这是一个非常简洁的选项,并且在我的特殊情况下看起来非常方便。
  • @Jayg713 可以肯定的是,当它最终被纳入 create-react-app 并成为主流时,我很兴奋。
猜你喜欢
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多