React中如何将API返回的JSON数组设置到state状态中?
代码修改方案
你原代码存在两个核心问题:
state中item的初始值类型错误,API返回的是JSON数组,初始值不应该设为空字符串,建议设为空数组- 你在
map遍历过程中反复调用setState,最终只会存储数组的最后一个元素,无法完整保存接口返回的所有数据
修改后的完整代码:
import React, { Component } from 'react'; import axios from 'axios' class Axios extends Component { constructor() { super(); this.state = { // 初始值设为空数组,存储接口返回的完整数组 countryList: [], // 可单独存储你需要的common名称,也可以直接从countryList取 commonName: '' } } componentDidMount() { axios.get('https://restcountries.com/v3.1/capital/lima') .then(response => { // 直接把接口返回的完整数组存到state中 this.setState({ countryList: response.data, // 该接口查询利马只会返回1条结果,直接取第一个元素的common名称 commonName: response.data[0]?.name.common || '' }) }) .catch(error => { alert(error); }); } prepare() { const { countryList } = this.state // 遍历处理数据,也可以直接取commonName字段使用 return countryList.map(country => ( <div key={country.cca2}> 国家通用名称:{country.name.common} </div> )) } render() { // 加个加载判断,避免数据没回来时报错 if (!this.state.countryList.length) return <div>加载中...</div> return ( <div>{this.prepare()}</div> ) } } export default Axios;
补充说明:
如果需要保留你原来的item字段命名,直接把上面的countryList替换成item即可,不影响逻辑。如果后续你需要处理多结果的返回,直接在prepare方法里遍历countryList就行,不需要在请求回调里处理数据存储逻辑。
内容的提问来源于stack exchange,提问作者user1202813
相关产品推荐
相关产品推荐

