reactjs - React fetch data in server before render -
i'm new reactjs, want fetch data in server, send page data client.
it ok when function getdefaultprops return dummy data {data: {books: [{..}, {..}]}}.
however not work code below. code execute in sequence error message "cannot read property 'books' of undefined"
- getdefaultprops
- return
- fetch
- {data: {books: [{..}, {..}]}}
however, expect code should run in 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> ); }
what you're looking componentwillmount
.
from documentation:
invoked once, both on client , server, before initial rendering occurs. if call
setstate
within method,render()
see updated state , executed once despite state change.
so this:
componentwillmount : function () { var data = this.getdata(); this.setstate({data : data}); },
this way, render()
called once, , you'll have data you're looking in initial render.
Comments
Post a Comment