【问题标题】:Uncaught (in promise) TypeError: items.map is not a function using reactUncaught (in promise) TypeError: items.map is not a function using react
【发布时间】:2019-09-19 07:25:41
【问题描述】:

尝试输出我的列表时出现以下错误 Uncaught (in promise) TypeError: items.map is not a function

尝试使用 map 输出我的 json 列表,但似乎失败了,我知道 this.state.data 包含 myjson,因为我能够 console.log 它。不明白为什么我得到这个错误。下面使用外部文件使用反应调用 json 知道它可能 eb 基本问题似乎无法正常工作

  JSON CODE

{
"vehicles": [
    {
        "id": "x",
        "modelYear": "98",
        "url": "/api/vehicle/tt",
        "media": [
            {
                "name": "vehicle",
                "url": "/images/1.jpg"
            }
        ]
    },
    {
        "id": "z",
        "modelYear": "99",
        "url": "/api/vehicle/ff",
        "media": [
            {
                "name": "vehicle",
                "url": "/images/2.jpg"
            }
        ]
    },

 ]
}

export const getData = (data) => {

return fetch('http://localhost:9968/api/vehicle')
.then(response => response.json())
.then((data) => {
return response.json()
})

  import { getData } from '../api';

  export default
  class VehicleList extends Component {

constructor(props) {
    super(props);

    this.state = {
        data : null
    }
}

async componentDidMount() {
    let response = await getData();
    this.setState({data: response})
    }

render() {
    if(this.state.data) {
        let items = this.state.data


        return  (
            <div>
            {items.map(item => <h4>{item.id}</h4>)}
            </div>
        )
    }

    return (<h1>Loading...</h1>);
}

}

【问题讨论】:

  • 每当您遇到这样的错误时,请始终调试您的代码并在您遇到错误的位置设置断点并查看变量包含的内容。在这种情况下,检查items 会显示它是一个具有单个“车辆”属性的对象。或者,使用console.log(JSON.stringify(items, null, 2)) 记录数据的形状。

标签: reactjs promise typeerror


【解决方案1】:

根据您共享的 JSON,它嵌套在 vehicles 下。你试过了吗:

{items.vehicles.map(item => <h4>{item.id}</h4>)}

【讨论】:

    【解决方案2】:

    您的数据属于一个对象,位于一个名为 vehicles 的键中。看起来你需要:

    render() {
        if(this.state.data) {
            let items = this.state.data.vehicles
    
    
            return  (
                <div>
                {items.map(item => <h4>{item.id}</h4>)}
                </div>
            )
        }
    
        return (<h1>Loading...</h1>);
    }
    

    【讨论】: