簡體   English   中英

為什么即使在 UseEffect 掛鈎中設置狀態后我的 React 狀態仍未定義?

[英]Why is my React state undefined even after setting the state in UseEffect hook?

所以這段代碼從父組件獲取經緯度,然后獲取國家代碼,然后根據該國家代碼獲取新聞文章,傳遞給子組件。 但是,當我嘗試向下傳遞數據時,我得到“紙張未定義”。 我是否正確設置狀態?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM