所以这段代码从父组件获取经纬度,然后获取国家代码,然后根据该国家代码获取新闻文章,传递给子组件。但是,当我尝试向下传递数据时,我得到“纸张未定义”。我是否正确设置了状态?
import React, {useState, useEffect} from 'react';
import { usePosition } from 'use-position';
import Article from './Article';
import './App.css'
const News = (lat, lng) => {
const API_KEY = `XXXXXXXXXXXXXXXXXXXXX`
var url;
var newsurl;
var country;
const [paper, setPaper] = useState();
useEffect(() =>{
if (typeof lat.lat !== "undefined" && typeof lat.lng !== "undefined"){
url = `https://api.opencagedata.com/geocode/v1/json?q=${lat.lat}%2C${lat.lng}&key=${API_KEY}&pretty=1`
}
async function getCountry(mUrl) {
const response = await fetch(mUrl);
const countryData = await response.json();
country = countryData.results[0].components["ISO_3166-1_alpha-2"];
newsurl = `https://newsapi.org/v2/top-headlines?country=${country.toLowerCase()}&apiKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`;
const response2 = await fetch(newsurl);
const newsData = await response2.json();
setPaper(newsData);
//newsData.articles.map((article) => console.log(article.title));
}
getCountry(url);
},[]);
console.log(paper)
return(
<div>
{paper.articles.map(article => (
<Article name={article.title}/>
)
)}
</div>
)
}
export default News;
最佳答案
第一个渲染(在 useEffect 完成之前)文件是未定义的(因为你 setState 没有参数)。所以像这样设置状态:
const [paper, setPaper] = useState(null);
在最后一次返回(渲染)中试试这个:
{paper && paper.articles.map(article => ( ....
或
{paper ? paper.article.map(... : <WaitComponent/>
并在定义第一个 url 测试之前用坐标重命名输入属性 lat、lng:
if (typeof coord.lat !== 'undefined' && typeof coord.lng !== 'undefined')
{
url = `https://api.opencagedata.com/geocode/v1/json?q=${coord.lat}%2C${coord.lng}&key=${API_KEY}&pretty=1`;
}
关于javascript - 为什么即使在 UseEffect Hook 中设置状态后我的 React 状态仍未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59845917/