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>;
}
}
Your initial data
state is String
., String
does not have method .map
, you need change your initial state from ''
to []
this.state = { data: [] };
.map
is not applicable to a String object. Consider changing 'data' to an array. .map
is a method that calls a function on every element of an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With