在渲染之前在服务器中重新获取数据

fin*_*oss 34 reactjs

我是reactjs的新手,我想在服务器中获取数据,以便它将向客户端发送包含数据的页面.

当函数getDefaultProps返回虚拟数据时,这是可以的,例如{data:{books:[{..},{..}]}}.

但是不能使用下面的代码.代码按此顺序执行,并显示错误消息"无法读取未定义的属性'书籍'

  1. getDefaultProps
  2. 返回
  3. {data:{books:[{..},{..}]}}

但是,我希望代码应按此顺序运行

  1. getDefaultProps
  2. {data:{books:[{..},{..}]}}
  3. 返回

任何的想法?

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>
    );
  }
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 19

你在寻找什么componentWillMount.

文档:

在初始渲染发生之前,在客户端和服务器上调用一次.如果setState在此方法中调用, render()将看到更新的状态,并且只有状态更改才会执行一次.

所以你会做这样的事情:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},
Run Code Online (Sandbox Code Playgroud)

这样,render()只会调用一次,并且您将获得初始渲染中要查找的数据.

  • ...但是如果getData触发异步请求? (39认同)
  • @nav对于异步请求,您将不得不设置一些初始状态,向用户指示正在获取数据(可能是加载图标).您仍然可以在`componentWillMount`中执行提取,并且在检索数据时,您可以再次设置该状态以指示数据已完成加载,并将其显示给用户. (8认同)
  • @MichaelParker componentWillMount 已弃用。您还有其他选择吗? (5认同)

Mah*_*our 8

一个非常简单的例子

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

在 React 中,props用于组件参数而不是用于处理数据。有一个单独的构造称为state. 每当您更新state组件时,基本上都会根据新值重新渲染自身。

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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 6

我用来从服务器接收数据并显示它的最佳答案

 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}/> 
                }
         ) }
Run Code Online (Sandbox Code Playgroud)