【发布时间】:2020-04-04 10:39:51
【问题描述】:
目前,我的应用程序能够从我的 API 获取数据。但是,我在迭代数据时遇到了麻烦,因此我可以通过状态显示它。我在控制台中不断收到以下错误消息:getSoups failed TypeError: Cannot read property 'map' of undefined。
引用如下代码:
getSoups() {
axios
.get('http://127.0.0.1:8000/api/soups/')
.then(response => {
console.log('soup response data', response);
response.data.soups.map(soup => ({
id: soup.id,
title: soup.title,
name: soup.name,
description: soup.description,
front_thumb_img_url: soup.front_thumb_img_url
}))
})
.then(soups => {
this.setState({
soups
});
})
.catch(error => {
console.log('getSoups failed', error);
});
}
整个组件:menu-container.js:
import React, { Component } from 'react';
import axios from 'axios';
import Soups from './soups-edited';
export default class MenuContainer extends Component {
constructor() {
super();
this.state = {
soups: []
};
this.getSoups = this.getSoups.bind(this);
}
getSoups() {
axios
.get('http://127.0.0.1:8000/api/soups/')
.then(response => {
console.log('soup response data', response.data.soups);
response.data.soups.map(soup => ({
id: soup.id,
title: soup.title,
name: soup.name,
description: soup.description,
front_thumb_img_url: soup.front_thumb_img_url
}))
})
.then(soups => {
this.setState({
soups
});
})
.catch(error => {
console.log('getSoups failed', error);
});
}
componentDidMount() {
this.getSoups();
}
render() {
const { soups } = this.state;
return (
<div className='soups'>
{ soups.map(soup => {
const { id, title, name, description,front_thumb_img_url } = soup;
return (
<ul key={id}>
<li>{title}</li>
<li>{name}</li>
<li>{description}</li>
<li>{front_thumb_img_url}</li>
</ul>
)
})}
</div>
);
}
}
【问题讨论】:
-
您可以将组件粘贴到您显示结果的位置吗?您最好在组件本身中进行映射。
-
尝试
console.log(response.data.soups)看看它是否被定义了。 -
@randomboiguyhere 当我只是 console.log(response) 它显示对象。但是对于 console.log(response.data.soups) 它是未定义的。
-
@JohnGartsu 那么为什么要使用
.soups?你不能用response.map()吗? -
我想
.soups部分是未定义的。我会尝试两件事:最初是console.log(response.data)。检查并确认该 JSON 对象有一个名为soups的属性。如果没有,这就是你的答案。
标签: reactjs django-rest-framework axios