繁体   English   中英

React useEffect in async function 调用数据问题,无法读取未定义错误的属性。 我该如何解决?

[英]React useEffect in async function call data problem, Cannot read properties of undefined error. How can i fixed?

** React useEffect in async function 调用数据问题。 **

无法读取未定义错误的属性。

我该如何解决? 我正在使用 axios 获取数据,但是由于数据迟到,因此在写入 dom 时会引发错误

 import React, { useState, useEffect } from "react";
    import { useParams, Link } from "react-router-dom";
    import axios from "axios";
    
    function CountryDetail() {
      const { countryCode } = useParams();
      const [country, setCountry] = useState([]);
    

      const getCountry = async () => {
        await axios
          .get(`https://restcountries.com/v3.1/alpha?codes=${countryCode}`)
          .then((res) => setCountry(res.data[0]));
      };
    
      useEffect(() => {
        getCountry();
      }, []);
      console.log(country);
    
      return (
        <>
          <div className="container">
            <div className="row ">
              <h1 className="text-center mt-4">Country Detail Page</h1>
    
              <div className="col-12">
                <img src={country.flags.png} alt={country.flags.png} />
                <h2>
                  {country.name.common} ( {country.cca3} )
                </h2>
    
                <h4>Kıta: {country.continents}</h4>
                <h5>Başkent: {country.capital[0]}</h5>
                <p>Nüfus: {country.population}</p>
              </div>
            </div>
    
            <div className="row">
              <Link to={"/"} className="mt-5 mx-auto col-4 btn btn-info">
                Back To Home Page
              </Link>
            </div>
          </div>
        </>
      );
    }
    
    export default CountryDetail;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM