React Fetch天气数据渲染时出现uncaught TypeError: map不是函数问题求助
问题分析
报错uncaught TypeError: this.state.posts.map is not a function的核心原因是:你请求的天气接口返回的是单个对象,而非数组,但你把这个对象直接赋值给了初始为数组的posts状态。对象没有map方法,所以调用时抛出错误。
另外代码还有两个小问题:
- 渲染时嵌套了
<li>标签,不符合HTML结构规范 - 你试图访问
post.temp,但接口返回的temp是在main对象内部,正确路径是post.main.temp
修复方案
以下提供两种可行的修复方式:
方式一:将状态改为存储单个天气对象
适合接口返回单个数据的场景,逻辑更直观:
import logo from './logo.svg'; import './App.css'; import React from 'react'; class App extends React.Component { state = { weather: null, // 初始设为null,标识未加载完成 }; componentDidMount() { fetch("https://mm214.com/demo.php") .then(response => response.json()) .then(data => { console.log(data); this.setState({ weather: data }); }) .catch(error => console.error(error)); } render() { const { weather } = this.state; // 未加载完成时显示占位内容 if (!weather) return <div>加载中...</div>; return ( <header> <h1>Weather</h1> <ul> <li key="temp">温度: {weather.main.temp}</li> {/* 如果需要显示天气描述等weather数组内的内容 */} {weather.weather.map(item => ( <li key={item.id}>{item.description}</li> ))} </ul> </header> ); } } export default App;
方式二:保持数组状态,将单个对象存入数组
如果你想沿用原有的数组结构,只需把返回的对象包装成数组:
import logo from './logo.svg'; import './App.css'; import React from 'react'; class App extends React.Component { state = { posts: [], }; componentDidMount() { fetch("https://mm214.com/demo.php") .then(response => response.json()) .then(postData => { console.log(postData); // 将单个对象转为数组存入状态 this.setState({ posts: [postData] }); }) .catch(error => console.error(error)); } render() { return ( <header> <h1>Weather</h1> <ul> {this.state.posts.map((post, index) => ( <li key={index}>温度: {post.main.temp}</li> ))} </ul> </header> ); } } export default App;
关键注意点
- 调用接口后先通过
console.log确认返回数据的结构,再针对性访问属性 - 渲染前最好做存在性判断,避免未加载完成时访问null/undefined的属性
- 列表项的
key尽量使用数据中唯一的标识(比如接口返回的id),没有的话再用索引
内容的提问来源于stack exchange,提问作者Tyro
相关产品推荐
相关产品推荐

