我正在创建一个显示API数据列表的简单反应代码。 但是,它在第27行返回了一个错误“未捕获的TypeError:this.state.items.map不是函数”。 你能告诉我原因吗?我只是出于安全原因更改了api密钥和网站名称。 请帮忙!
import React from "react";
import Form from "./components/Form.js";
const API_KEY = "123123";
class App extends React.Component {
//initialize state
state = {
items: []
};
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const state = e.target.elements.state.value;
const api_call = await fetch(`https://test.com/api/events?
locationIds=${city},${state}&client=${API_KEY}`);
const data = await api_call.json();
console.log(data);
//set the values of the state
this.setState({
items: data
});
}
render() {
const itemList = this.state.items.map(
(item, index) =>
<li
key={index}>
{item}
</li>
)
return (
<div>
<p>Hello!</p>
<h1>hi</h1>
<Form getWeather={this.getWeather}/>
<ul>
{itemList}
</ul>
</div>
)
}
}
export default App;
{data: Array(132), success: true}
data: Array(132)
[0 … 99]
0: {id: 110503, link: ""…}
1: {id: 106100, link: ""..}
2: {id: 109675, link: ""..}
答案 0 :(得分:0)
首先尝试检查state.item,例如:
if(this.state.items){
const itemList = this.state.items.map((item, index) => (
<li key={index}> {item} </li>
)
}
答案 1 :(得分:0)
getWeather api是异步的,这意味着在加载数据之前调用渲染函数,因此在运行map函数之前需要进行检查
const itemList = (this.state.items && this.state.items.length > 0) ?
this.state.items.map(
(item, index) =>
<
li key = {
index
} > {
item
} <
/li>
) : ''