无法访问对象 api 响应中的第二个子对象

Cant access second child object of an object api response in react

我无法访问通过 api 响应生成的对象的第二个子对象。这是我正在使用 https://www.weatherapi.com/ 的天气 api。在 Display.js 下查看更多说明。

App.js

import React,{useState} from 'react';
import Navbar from './Navbar.js';
import Display from './Display.js'
function App() {
  const[placeName,setPlaceName] = useState('Raipur')
  let key = 'not gonna tell';

  return (
   <>
   <Navbar setPlaceName={setPlaceName} />
   <Display key={key} placeName={placeName} />
   </>
  );
}

export default App;

Navbar.js

import React from 'react';

function Navbar(props) {
  return(
   <>
    <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
  <div className="container-fluid">
    <a className="navbar-brand" href="/">Navbar</a>
    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="/navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span className="navbar-toggler-icon"></span>
    </button>
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav me-auto mb-2 mb-lg-0">
        <li className="nav-item">
          <a className="nav-link active" aria-current="page" href="/">Home</a>
        </li>
        <li className="nav-item">
          <a className="nav-link" href="/">Link</a>
        </li>
        <li className="nav-item dropdown">
          <a className="nav-link dropdown-toggle" href="/" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
          </a>
          <ul className="dropdown-menu" aria-labelledby="navbarDropdown">
            <li><a className="dropdown-item" href="/">Action</a></li>
            <li><a className="dropdown-item" href="/">Another action</a></li>
            <li><hr className="dropdown-divider"/></li>
            <li><a className="dropdown-item" href="/">Something else here</a></li>
          </ul>
        </li>
        <li className="nav-item">
          <a className="nav-link disabled">Disabled</a>
        </li>
      </ul>
      <form className="d-flex">
        <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"/>
        <button onClick={props.setPlaceName} className="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>
   </>
  );
}

export default Navbar;

Display.js

import React,{useState,useEffect} from 'react';

function Display(props) {
  
  const[weatherInfo,setWeatherInfo] = useState([]);
  
  const getWeatherInfo = async () =>{
    let url =`https://api.weatherapi.com/v1/current.json?key=${props.key}&q=${props.placeName}&aqi=no`;
    let weatherInfo = await fetch(url);
    let parsedweatherInfo = await weatherInfo.json();
    setWeatherInfo(parsedweatherInfo.location);
  }
  // eslint-disable-next-line
  useEffect(async () =>{
    getWeatherInfo();
  },[])
  return (
    <>
    <div className="container">
    <div className="row"> 
    {Object.values(weatherInfo).map((key,value)=>{
    return(
     <div className="col" key={key}>
     {key} 
     </div>
    )  
    })} 
    </div>
    </div>
    </>
  )
}

export default Display;

在这里,当我尝试通过函数 getWeatherInfo 解析下面给出的对象的 current 对象时,我得到一个错误提示 Objects are作为 React 子级无效(找到:[object Promise])。如果您打算呈现子项集合,请改用数组。 但是当我尝试解析位置对象时,它起作用了。对我来说当前对象比位置更重要。

示例响应

{
    "location": {
        "name": "London",
        "region": "City of London, Greater London",
        "country": "United Kingdom",
        "lat": 51.52,
        "lon": -0.11,
        "tz_id": "Europe/London",
        "localtime_epoch": 1631360600,
        "localtime": "2021-09-11 12:43"
    },
    "current": {
        "last_updated_epoch": 1631359800,
        "last_updated": "2021-09-11 12:30",
        "temp_c": 21.0,
        "temp_f": 69.8,
        "is_day": 1,
        "condition": {
            "text": "Partly cloudy",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
            "code": 1003
        },
        "wind_mph": 11.9,
        "wind_kph": 19.1,
        "wind_degree": 250,
        "wind_dir": "WSW",
        "pressure_mb": 1017.0,
        "pressure_in": 30.03,
        "precip_mm": 0.0,
        "precip_in": 0.0,
        "humidity": 64,
        "cloud": 50,
        "feelslike_c": 21.0,
        "feelslike_f": 69.8,
        "vis_km": 10.0,
        "vis_miles": 6.0,
        "uv": 5.0,
        "gust_mph": 10.5,
        "gust_kph": 16.9
    }
}

在您的 App.js 组件中,您使用 key 关键字作为道具名称。 React 在其协调算法中使用此关键字。它通常在渲染元素数组时使用。

如果你 console.log(props) 你实际上可以看到 key prop 不在 props 对象中。当你发出请求时,它 returns 这个对象,而不是你期望的 return:

{
 error: {
  code: 1002,
  message: "API key is invalid or not provided."
 }
}

并且当您在 Display.js 组件中对其进行迭代时,您将该对象分配为 React 子对象。

所以尝试为道具使用不同的名称,例如 api_key

更新:

current 对象内部有一个对象,因此 React 会抛出您提到的错误。你可以做的是在 map 函数内部,检查 key 是否是一个对象,然后也解析该对象。这样的事情可能会奏效:

{Object.values(weatherInfo).map((key, value) => {
     let result;
     if (typeof key === "object") {
         result = Object.values(key).join(" ");
     } else {
         result = key;
     }
     return (
         <div className="col" key={value}>
             {result}
         </div>
     );
})}`

此外,您也可以查看 答案