【发布时间】:2019-05-29 05:53:18
【问题描述】:
我的代码中出现错误“this.state.UserData.map”不是函数。我想使用 fetch 从数据库中获取列表。我想我忘记了什么。 请帮我删除这个错误。提前致谢。 这是我显示列表的完整代码...
import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
constructor(props){
super(props);
this.state={ UserData:[] };
this.headers=[
{key:1,label:'Name'},
{key:2,label:'Department'},
{key:3,label:'Marks'},
];
}
componentDidMount(){
fetch("https://www.veomit.com/test/zend/api/fetch.php")
.then(response => {
return response.json();
})
.then(result => {
this.setState({
UserData:result
})
.catch(error => {
console.log(
"An error occurred while trying to fetch data from Foursquare: " +error
);
});
});
}
render(){
return(
<div>
<table className="table table-bordered">
<thead>
<tr>
{
this.headers.map(function(h) {
return (
<th key = {h.key}>{h.label}</th>
);
})
}
</tr>
</thead>
<tbody>
{
this.state.UserData.map(function(item){
return (
<tr>
<td>{item.name}</td>
<td>{item.department}</td>
<td>{item.marks}</td>
</tr>
);
})
}
</tbody>
</table>
</div>
);
}
}
````````
【问题讨论】:
-
在
.then(result => {...})中,执行console.log(result)。这是什么? -
表示
this.state.UserData不是数组。查看URL,它是一个对象。 -
你能告诉我
console.log(result)是什么吗?可能的原因是您的结果不是Array, -
是的,你是对的,它不是一个数组。我在控制台中获取对象。
-
你的代码给了我'Cannot read property 'name' of null'错误。
标签: javascript arrays reactjs object ecmascript-6