this.state.items.map 不是一个函数.可能的解决方案是什么



我正在创建一个简单的反应代码,显示API数据列表。但是,它在第 27 行返回错误"Uncatch 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: ""..}

首先尝试检查状态项目,如下所示:

if(this.state.items){
  const itemList = this.state.items.map((item, index) => (
    <li key={index}> {item} </li>
  )
}

getWeather api是异步的,这意味着渲染函数在加载数据之前被调用,因此在运行map函数之前需要检查

const itemList = (this.state.items && this.state.items.length > 0) ?
this.state.items.map(
    (item, index) =>
    <
    li key = {
        index
    } > {
        item
    } <
    /li>
) : ''

最新更新