我的代码“ this.state.UserData.map”中没有错误,不是函数。我想使用提取从数据库中获取列表。我想我忘记了一些东西。 请帮助我删除此错误。提前致谢。 这是我显示清单的完整代码...
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>
);
}
}
````````
答案 0 :(得分:2)
请替换您的代码,希望对您有用。
谢谢
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'},
];
}
componentWillMount() {
fetch("https://www.veomit.com/test/zend/api/fetch.php")
.then(response => {
return response.json();
})
.then(result => {
this.setState({
UserData: result
});
})
.catch(function(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.length > 0 ?
this.state.UserData.map((item,index) => (
<tr key={index}>
<td>{item.name}</td>
<td>{item.department}</td>
<td>{item.marks}</td>
</tr>
))
) : (
<tr>
<td colspan="3">No record found.</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
}
````````
答案 1 :(得分:0)
数据是一个对象-您需要使用Object.values
将其转换为数组:
UserData: Object.values(result)
答案 2 :(得分:0)
响应不是数组。您需要将响应服务器转换为对象数组才能使用map
响应必须这样。您可以告诉后端服务进行此类更改,或将其转换为您的状态
[{name: 'John Doe', department: 'CEO', marks: 'title' } , {....} ]