【问题标题】:Lifecycle issue on axios call to an external APIaxios 调用外部 API 的生命周期问题
【发布时间】:2021-11-29 16:15:10
【问题描述】:

我正在尝试对 react 功能组件进行 axios 调用,但生命周期让我很头疼,因为它不断返回“无法读取未定义的属性”。 我尝试使用条件渲染以及等待/异步函数,但似乎没有任何效果。 有人可以告诉我我做错了什么吗? 谢谢

import axios from "axios";
import { useParams } from "react-router-dom";

const SingleCountry = () => {
  let params = useParams();
  const [singleCountry, setSingleCountry] = useState([]);

  useEffect(() => {
    const getSingleCountry = () => {
      axios
        .get(`https://restcountries.com/v3.1/name/${params.name}`)
        .then((country) => setSingleCountry(country.data))
        .catch((error) => console.log(`${error}`));
    };
    getSingleCountry();
  }, []);

  return (
    <div>
      <h1>Single Country</h1>
      {singleCountry.length > 0 && (
        <div>
          <h3>{singleCountry.name.common}</h3>
        </div>
      )}
    </div>
  );
};

export default SingleCountry; 

【问题讨论】:

    标签: javascript reactjs axios react-lifecycle


    【解决方案1】:

    您的渲染方法正在尝试访问singleCountry.name.common,但是,您的状态变量是一个数组。

    将渲染函数更改为:

    {singleCountry.map(country => <div><h3>{country.name.common}</h3></div>)}
    

    【讨论】:

    • 谢谢!就是这样。我没有看到问题的正确部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2011-10-06
    相关资源
    最近更新 更多