类型错误:无法读取未定义的属性“map”
2020-02-12
98
import React, { Component } from "react";
import axios from "axios";
class Abc extends Component {
constructor(props) {
super(props);
this.state = { descriptions: [] };
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
this.setState({ descriptions: response.data });
if (response.data) {
var rdata = response.data;
for (var r = 0; r < rdata.length; r++) {
if (r === 0) {
// console.log(rdata[r]);
// const {rdata} this.dataEle = rdata[r]
console.log(this.dataEle.name);
}
}
}
})
.catch(error => {
console.log(error);
});
}
render() {
const { dataEle } = this.setState;
return (
<div>
{dataEle.map((description, index) => (
<p key={index}>{description.description}</p>
))}
</div>
);
}
}
export default Abc;
3个回答
dataEle
在第一次渲染中未定义(以及在获取之前的任何后续渲染)。您也没有在渲染函数中正确地对其进行解构。我认为您可能想要解构
descriptions
。
import React, { Component } from "react";
import axios from "axios";
class Abc extends Component {
constructor(props) {
super(props);
this.state = {
descriptions: [],
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
this.setState({ descriptions: response.data });
// if (response.data) {
// var rdata = response.data;
// for (var r = 0; r < rdata.length; r++) {
// if (r === 0) {
// // console.log(rdata[r]);
// // const {rdata} this.dataEle = rdata[r]
// console.log(this.dataEle.name);
// }
// }
// }
})
.catch(error => {
console.log(error);
});
}
render() {
const { descriptions } = this.state;
return (
<div>
// {descriptions.map((description, index) => (
// <p key={index}>{description.description}</p> // response data objects don't have a description property!
// ))}
{descriptions[1] && descriptions[1].name}
</div>
);
}
}
export default Abc;
此外,响应数据形状上没有
description
属性,但老实说,我不太确定您想用 for 循环做什么,它会引发错误。
Drew Reese
2020-02-12
您的代码中存在相当多的问题。
据推测您的意图是:
const { dataEle } = this.setState;
变为
const { descriptions = [] } = this.state;
grantnz
2020-02-12
请尝试:
class Abc extends Component {
constructor(props) {
super(props);
this.state = {
descriptions: [] ;
}
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
this.setState({ descriptions: response.data });
})
.catch(error => {
console.log(error);
});
}
//for mapping**
return (
<div>
{this.sate.descriptions.map((description, index) => (
<p key={index}>{description.description}</p>
))}
</div>
);
}
}
Vijay Gehlot
2020-02-12