不能在react中访问对象api响应的第二个子对象



我无法访问通过api响应生成的对象的第二个子对象。这是我正在使用的天气api https://www.weatherapi.com/。查看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对象时,我得到一个错误说对象作为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道具不在道具对象中。当您发出请求时,它返回这个对象,而不是您期望的返回:

{
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>
);
})}`

你也可以检查这个答案

相关内容

  • 没有找到相关文章

最新更新