[英]Why is my React state undefined even after setting the state in UseEffect hook?
So this code is getting latitude and longitude passed down from a parent component and then fetching a country code and then fetching news articles based on that country code to pass down to a child.所以这段代码从父组件获取经纬度,然后获取国家代码,然后根据该国家代码获取新闻文章,传递给子组件。 However, when I try to pass the data down I am getting "paper is undefined".但是,当我尝试向下传递数据时,我得到“纸张未定义”。 Am I setting the state correctly?我是否正确设置状态?
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;
The first render (before useEffect done) paper is undefined (because you setState without params).第一个渲染(在 useEffect 完成之前)文件是未定义的(因为你 setState 没有参数)。 So set state like this:所以像这样设置状态:
const [paper, setPaper] = useState(null);
in the last return (render) try this:在最后一次返回(渲染)中试试这个:
{paper && paper.articles.map(article => ( ....
or要么
{paper ? paper.article.map(... : <WaitComponent/>
and rename input props lat, lng with coord and before define first url test:并在定义第一个 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`;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.