React fetch data in server before render

前端 未结 8 1815
自闭症患者
自闭症患者 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 (
            <li key={book.key}>{book.name}</li>
          );
        });
    
        return (
          <div>
            <ul>
              {books}
            </ul>
          </div>
        );
      }
    });
    
    0 讨论(0)
  • 2020-12-02 18:55

    You can use redial package for prefetching data on the server before attempting to render

    0 讨论(0)
  • 2020-12-02 18:57

    The best answer I use to receive data from server and display it

     constructor(props){
                super(props);
                this.state = {
                    items2 : [{}],
                    isLoading: true
                }
    
            }
    
    componentWillMount (){
     axios({
                method: 'get',
                responseType: 'json',
                url: '....',
    
            })
                .then(response => {
                    self.setState({
                        items2: response ,
                        isLoading: false
                    });
                    console.log("Asmaa Almadhoun *** : " + self.state.items2);
                })
                .catch(error => {
                    console.log("Error *** : " + error);
                });
        })}
    
    
    
        render() {
           return(
           { this.state.isLoading &&
                        <i className="fa fa-spinner fa-spin"></i>
    
                    }
                    { !this.state.isLoading &&
                //external component passing Server data to its classes
                         <TestDynamic  items={this.state.items2}/> 
                    }
             ) }
    
    0 讨论(0)
  • 2020-12-02 18:58

    Responded to a similar question with a potentially simple solution to this if anyone is still after an answer, the catch is it involves the use of redux-sagas:

    https://stackoverflow.com/a/38701184/978306

    Or just skip straight to the article I wrote on the topic:

    https://medium.com/@navgarcha7891/react-server-side-rendering-with-simple-redux-store-hydration-9f77ab66900a

    0 讨论(0)
  • 2020-12-02 19:00

    A very simple example of this

    import React, { Component } from 'react';
    import { View, Text } from 'react-native';
    
    export default class App extends React.Component  {
    
        constructor(props) {
          super(props);
    
          this.state = {
            data : null
          };
        }
    
        componentWillMount() {
            this.renderMyData();
        }
    
        renderMyData(){
            fetch('https://your url')
                .then((response) => response.json())
                .then((responseJson) => {
                  this.setState({ data : responseJson })
                })
                .catch((error) => {
                  console.error(error);
                });
        }
    
        render(){
            return(
                <View>
                    {this.state.data ? <MyComponent data={this.state.data} /> : <MyLoadingComponnents /> }
                </View>
            );
        }
    }
    
    0 讨论(0)
  • 2020-12-02 19:05

    I've just stumbled upon this problem too, learning React, and solved it by showing spinner until the data is ready.

        render() {
        if (this.state.data === null) {
            return (
                <div className="MyView">
                    <Spinner/>
                </div>
            );
        }
        else {
            return(
                <div className="MyView">
                    <ReactJson src={this.state.data}/>
                </div>
            );
        }
    }
    
    0 讨论(0)
提交回复
热议问题