我正在学习React,现在我正在尝试获取resquest并使用map列表,但是当我运行此代码时,他们会出现此错误“Unhandled Rejection(TypeError):this.state.features.map不是函数” 。我已经搜索了这个,但我不知道它是怎么回事。
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中,只需执行以下操作:
componentWillMount() {
fetch("http://demo6085176.mockable.io/features")
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({ features: json.features });
});
}
您从API获得的响应是一个对象,其中包含features
的键,该键是您想要的数据的对象数组。