[英]ReactJS “Unhandled Rejection (TypeError): this.state.features.map is not a function”
I'm learning React and now i'm trying do a get resquest and list with map but when I run this code they come up with this error "Unhandled Rejection (TypeError): this.state.features.map is not a function". 我正在学习React,现在我尝试获取获取请求并使用map进行列表,但是当我运行此代码时,他们会遇到此错误“未处理的拒绝(TypeError):this.state.features.map不是函数” 。 I already search this but I'm not undertand what its going on. 我已经搜索过了,但我不知道它在发生什么。
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
features: [{
id: 1,
name: 'Test',
count: 1
}]
}
}
componentWillMount() {
fetch("http://demo6085176.mockable.io/features")
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({
features: json,
});
});
console.log(this.state.features)
}
render() {
return (
<div className="App">
<ul>
{
this.state.features.map(function(feature){
return (
<li key={feature.id}><button type="button">Upvote</button> ({feature.count}) <span>{feature.name}</span></li>
)
})
}
</ul>
</div>
);
}
}
export default App;
In your componentWillMount, just do this: 在您的componentWillMount中,只需执行以下操作:
componentWillMount() {
fetch("http://demo6085176.mockable.io/features")
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ features: json.features });
});
}
The response you get from the API is an object which has a key of features
which is an array of objects of the data you want. 您从API获得的响应是一个具有关键features
的对象,该features
是所需数据的对象数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.