React fetch data in server before render

前端 未结 8 1987
自闭症患者
自闭症患者 2020-12-02 18:29

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

8条回答
  •  借酒劲吻你
    2020-12-02 18:55

    In React, props are used for component parameters not for handling data. There is a separate construct for that called state. Whenever you update state the component basically re-renders itself according to the new values.

    var BookList = React.createClass({
      // Fetches the book list from the server
      getBookList: function() {
        superagent.get('http://localhost:3100/api/books')
          .accept('json')
          .end(function(err, res) {
            if (err) throw err;
    
            this.setBookListState(res);
          });
      },
      // Custom function we'll use to update the component state
      setBookListState: function(books) {
        this.setState({
          books: books.data
        });
      },
      // React exposes this function to allow you to set the default state
      // of your component
      getInitialState: function() {
        return {
          books: []
        };
      },
      // React exposes this function, which you can think of as the
      // constructor of your component. Call for your data here.
      componentDidMount: function() {
        this.getBookList();
      },
      render: function() {
        var books = this.state.books.map(function(book) {
          return (
            
  • {book.name}
  • ); }); return (
      {books}
    ); } });

提交回复
热议问题