Answer the question
In order to leave comments, you need to log in
How not to get undefined in react.js?
Hello, the essence of the problem is that I load json from the server via ajax, and parse it through react for rendering, and at the first start I always get undefined, and then I get the data as it should be. How to fix the problem?
The code:
var Game = React.createClass({
getInitialState: function() {
return {data: []};
},
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
console.log(data[0]._id);
this.setState({data: data[0]});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="gameBox">
<h1> Game id: {this.props._id}</h1>
<Bet data={this.state.data} />
</div>
);
}
});
//Comment list = bet
var Bet = React.createClass({
render: function() {
// при первом выводе через консоль тут получаю undefined, после уже получаю объект
console.log(this.props.data.bets)
var items = this.props.data.bets.map(function(item) {
return (
<Item name={item.name}/>
);
});
return (
<div className="bet">
{items}
</div>
);
}
});
//Comment = item
var Item = React.createClass({
render: function() {
return (
<div className="item">
<p> id: {this.props.id} </p> <br/>
<p> lowestPrice: {this.props.lowestPrice} </p> <br/>
<p> type: {this.props.type}</p> <br/>
<p> icon_url: {this.props.icon_url} </p> <br/>
<p> name: {this.props.name} </p> <br/>
<hr/>
</div>
);
}
});
React.render(
<Game url="game" pollInterval={2000} />,
document.getElementById('main')
);
Answer the question
In order to leave comments, you need to log in
And what is output to the console when console.log(this.props.data) for the first and subsequent times?
That's right, the first time your component Game
is loaded without data, because the initial state data
is an empty array, and you are trying to take a property bets
in the component Bet
.
After the first render, the event fires componentDidMount
and the data is loaded -> the state changes.
If I understood everything correctly, you should change the property data
in the method getInitialState
to be an object and not an array and add a check when passing data to the component Bet
:
{this.state.data.bets && <Bet data={this.state.data} />}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question