I'm new to reactjs, I want to fetch data in server, so that it will send page with data to client.
It is OK when the function getDefaultProps return dummy data like this {data: {books: [{..}, {..}]}}.
However not work with code below. The code execute in this sequence with error message "Cannot read property 'books' of undefined"
- getDefaultProps
- return
- fetch
- {data: {books: [{..}, {..}]}}
However, I expect the code should run in this sequence
- getDefaultProps
- fetch
- {data: {books: [{..}, {..}]}}
- return
Any Idea?
statics: {
fetchData: function(callback) {
var me = this;
superagent.get('http://localhost:3100/api/books')
.accept('json')
.end(function(err, res){
if (err) throw err;
var data = {data: {books: res.body} }
console.log('fetch');
callback(data);
});
}
getDefaultProps: function() {
console.log('getDefaultProps');
var me = this;
me.data = '';
this.fetchData(function(data){
console.log('callback');
console.log(data);
me.data = data;
});
console.log('return');
return me.data;
},
render: function() {
console.log('render book-list');
return (
<div>
<ul>
{
this.props.data.books.map(function(book) {
return <li key={book.name}>{book.name}</li>
})
}
</ul>
</div>
);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…