未捕获的TypeError:this.state.data.map不是函数
问题描述:
我是React的新手,看过一些类似的问题,但没有找到为什么会这样。我得到一个未捕获的TypeError:this.state.data.map不是一个函数。
这是代码。请帮助找出问题所在。
I am new to React, have seen some of the similar issues, but didn’t find why this happens. I am getting an "Uncaught TypeError: this.state.data.map is not a function". Here is the code. Please, help to find what is the problem.
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>;
}
}
答
您的initial data
state is String
。, String
没有方法 .map
,您需要将初始状态从''
更改为 [ ]
Your initial data
state is String
., String
does not have method .map
, you need change your initial state from ''
to []
this.state = { data: [] };