ReactJS quot;Unhandled Rejection (TypeError): this.state.features.map is not a functionquot;(ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数)
问题描述
我正在学习 React,现在我正在尝试使用 map 执行 get 请求和列表,但是当我运行此代码时,他们会遇到此错误Unhandled Rejection (TypeError): this.state.features.map不是函数".我已经搜索过这个,但我不明白发生了什么.
I'm learning React and now I'm trying to do a get request 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 have already searched this but I do not understand what is 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.
这篇关于ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数"


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01