未捕获的类型错误:this.state.data.map不是一个函数
Uncaught TypeError: this.state.data.map is not a function
我是React新手,见过一些类似的问题,但不知道为什么会发生这种情况。我得到一个"未捕获的类型错误:this.state.data.map不是一个函数"。下面是代码。请帮忙找出问题所在。
class Audienses extends React.Component {
constructor (props)
{
super(props);
this.state = {
data: ''
};
this.loadFromServer = this.loadFromServer.bind(this);
this.childeDelete = this.childeDelete.bind(this);
this.childeEdit = this.childeEdit.bind(this);
}
loadFromServer () {
var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
this.setState({ data: data });
}.bind(this);
xhr.send();
}
componentDidMount() {
this.loadFromServer();
}
render () {
var audienses = this.state.data.map((value, index) => (
<OneElement key={value.id} audience={value.audience} description={value.description} />
));
/* or like this
var audienses = this.state.data.map(function(s) {
<OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} />
}).bind(this);
*/
return
<div>
<h1>Audiences</h1>
<table id="services">
<tr>
<th>Audience</th>
<th>Description</th>
<th></th>
<th></th>
</tr>
<tbody>
{audienses}
</tbody>
</table>
</div>;
}
}
您的初始data
状态为String
, String
没有.map
方法,您需要将初始状态从''
更改为[]
this.state = { data: [] };
.map
不适用于String对象。考虑将'data'更改为数组。.map
是对数组的每个元素调用函数的方法。
我在react-redux中也有同样的错误。
问题是当我在添加/产品页面添加新产品并点击后退按钮时,主页的组件显示此错误
home_container.js:8 Uncaught TypeError: products.product.map is not a function
renderItems = (products) => (
products.product ?
products.product.map(item => (
<ProductItem {...item} key = { item._id } />
))
: null
)
解决方案我从节点服务器传递{}而不是[]
因此,当您在react-redux中遇到这种类型的错误时,请首先检查从服务器传递到该字段的内容,并检查该特定组件的reducer
首先必须将数据分割为一个数组,然后才能使用map函数。而不是
this.state.data.map
使用this.state.data.split('').map()
如果您的数据是字符串类型,那么您必须使用this.state.data.split('').map(ch=>{ console.log('Hello from map') })
我也遇到了同样的问题,但在我的情况下,这是因为在从控制器获取数据期间缺少JSON函数的括号。
fetch("https://localhost:44361/Api/Department").then(res=>res.json())
.then(result => {
this.setState({Departments:result});
}
);
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 我可以在json对象中添加一个函数吗
- Javascript使函数一个接一个地执行
- 是JavaScript中的函数一个对象
- 两个几乎相等的jQuery函数;一个适用于IE,一个不适用于IE
- 两个Javascript函数一个window.onload=Custom.init;和一个window.onload=f
- 使javascript加载函数一个接一个地执行
- 如何通过两个嵌套的匿名函数(一个带有超时的事件处理程序)传递变量
- 为什么我不能让两个jQuery函数一个在另一个里面呢?
- 给函数一个变量名,而不是它的值
- 如何使用嵌入函数(一个滚动页由Pete - peachananr)
- 是否有可能给JavaScript函数一个类型/类?
- 确保两个函数一个接一个地执行,其中第一个函数内部有一个异步调用
- 两个不同的ajax函数一个接一个调用返回相同的值
- jQuery第一次更改函数一个工作
- 给这个函数一个id
- 如何给回调函数一个值一个变量在特定时刻
- 使用回调使两个函数一个接一个地运行
- 两个函数(一个用php)是否可以用“;onclick”;
- 两个几乎相同的函数.一个函数用Queue进行排队.Jquery效果在queued函数上不起作用.为什么