React函数组件axios调用外部API时生命周期相关undefined报错问题
错误原因
- 缺失核心React API导入:代码中使用了
useState、useEffect两个Hook,但没有从react包中导入,会直接抛出未定义错误。 - 接口返回数据结构理解错误:
https://restcountries.com/v3.1/name/接口返回的是国家对象数组,你直接把数组赋值给singleCountry状态,调用singleCountry.name时,数组本身没有name属性,自然触发can not read property of undefined报错。你之前写的条件渲染singleCountry.length > 0会在接口返回后判定为真,触发渲染但因为变量是数组依然报错。 - useEffect依赖项缺失:路由参数
params.name没有加入useEffect依赖数组,当路由参数变化时不会重新触发请求拉取对应国家数据。
修复后代码
import axios from "axios"; import { useParams } from "react-router-dom"; // 补全React Hook导入 import { useState, useEffect } from "react"; const SingleCountry = () => { let params = useParams(); // 初始值设为null,语义更清晰,存储单个国家对象而非数组 const [singleCountry, setSingleCountry] = useState(null); // 依赖项加入params.name,参数变化时自动重新请求 useEffect(() => { const getSingleCountry = () => { axios .get(`https://restcountries.com/v3.1/name/${params.name}`) .then((country) => { // 取返回数组的第一个元素作为单个国家数据 setSingleCountry(country.data[0]) }) .catch((error) => console.log(`${error}`)); }; getSingleCountry(); }, [params.name]); return ( <div> <h1>Single Country</h1> {/* 条件渲染判断singleCountry是否存在 */} {singleCountry && ( <div> <h3>{singleCountry.name.common}</h3> </div> )} </div> ); }; export default SingleCountry;
内容的提问来源于stack exchange,提问作者ihatepineapple
相关产品推荐
相关产品推荐

