为什么在UseEffect挂钩中设置状态后,我的React状态仍未定义?

时间:2020-01-21 17:01:09

标签: javascript reactjs

因此,此代码是从父组件传递下来的纬度和经度,然后获取国家/地区代码,然后根据该国家/地区代码获取新闻报道,以传递给孩子。但是,当我尝试向下传递数据时,我得到“纸张未定义”。我可以正确设置状态吗?

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;

1 个答案:

答案 0 :(得分:1)

第一个渲染(在useEffect完成之前)纸张是未定义的(因为setState没有参数)。如此设置状态:

 const [paper, setPaper] = useState(null);   

在最后一个返回(呈现)中尝试以下操作:

 {paper && paper.articles.map(article => ( ....

 {paper ? paper.article.map(... : <WaitComponent/>

并在定义第一个url测试之前,用coord重命名输入道具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`;
}