ReactJS“未处理的拒绝(TypeError):this.state.features.map不是函数"
问题描述:
我正在学习React,现在我尝试获取获取请求并使用map列出,但是当我运行此代码时,他们会遇到此错误未处理的拒绝(TypeError):this.state.features.map不是功能".我已经搜索过了,但我不知道它在发生什么.
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". 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;
答
在您的componentWillMount中,只需执行以下操作:
In your componentWillMount, just do this:
componentWillMount() {
fetch("http://demo6085176.mockable.io/features")
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ features: json.features });
});
}
您从API获得的响应是一个对象,该对象的键为 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.