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"

  1. getdefaultprops
  2. return
  3. fetch
  4. {data: {books: [{..}, {..}]}}

however, expect code should run in sequence

  1. getdefaultprops
  2. fetch
  3. {data: {books: [{..}, {..}]}}
  4. 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

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -