When i used to fetch data from json api its throwing "Unexpected token" error. Below, i've added my code what i have tried so far. Get me out from this issue. I'm trying to solve this problem long time.
Here,
var Demo = React.createClass({
render: function() {
getInitialState:function(){
return {
data:[]
};
},
componentDidMount: function () {
$.ajax({
url: "http://www.w3schools.com/angular/customers.php"
}).done(function(data) {
this.setState({data: data})
});
},
return (
<div>
{this.props.data.map(function(el,i) {
return <div key={i}>
<div>{el.Name}</div>
<div>{el.City}</div>
<div>{el.Country}</div>
</div>;
}
</div>
);
}
});
var Stream = React.createClass({
render: function() {
return (
<div>
<div className="scrollContent ">
<Demo />
</div>
</div>
);
}
});
You have several errors in your code
getInitialState
and componentDidMount
from render
method, these methods should be as children of your component ( Demo
) class but not as children of render
method dataType: 'json'
to $.ajax
, because now it returns string, but in your case you need get json
this.setState
in .done
you should set this
to .done
callback, because now this
refers to $.ajax
object not Demo
, you can use .bind
method to do it. this.props.data
to this.state.data
because data located in state object not in props records
property use it instead of just data
var Demo = React.createClass({
getInitialState:function() {
return {
data :[]
};
},
componentDidMount: function () {
$.ajax({
url: "http://www.w3schools.com/angular/customers.php",
dataType: 'json'
}).done(function(response) {
this.setState({ data: response.records });
}.bind(this));
},
render: function() {
var customers = this.state.data.map(function(el,i) {
return <div key={i}>
<div>{el.Name}</div>
<div>{el.City}</div>
<div>{el.Country}</div>
</div>
});
return <div>{ customers }</div>;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.