reactjs - React 在渲染之前在服务器中获取数据

标签 reactjs

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

当函数 getDefaultProps 返回这样的虚拟数据时就可以了:{data: {books: [{..}, {..}]}}。

但是不适用于下面的代码。代码按此顺序执行,并显示错误消息“无法读取未定义的属性‘books’”

  1. 获取默认属性
  2. 返回
  3. 获取
  4. {数据:{书籍:[{..},{..}]}}

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

  1. 获取默认属性
  2. 获取
  3. {数据:{书籍:[{..},{..}]}}
  4. 返回

有什么想法吗?

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>
    );
  }

最佳答案

您正在寻找的是componentWillMount

来自documentation :

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

所以你会做这样的事情:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

这样,render() 将仅被调用一次,并且您将在初始渲染中获得所需的数据。

关于reactjs - React 在渲染之前在服务器中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30929679/

相关文章:

javascript - 无法正确配置webpack 2.2.1,不断抛出WebpackOptionsValidationError

javascript - 表单上的 ReactJS onSubmit 不起作用

reactjs - react 路由器自动添加查询字符串参数

javascript - React 中的 useEffect 清理函数中的 refs 数组包含空值

javascript - 如何使用react-router v6在组件内传递props

javascript - 'style ="border:none; overflow:hidden; height:80px"' 通过 python re.sub 到 js 对象

javascript - 使用高阶组件进行身份验证时如何延迟检查 redux 存储

javascript - 在 props 对象之外传递 "props"是反模式吗?

reactjs - 如何测试 enzyme 中子元素的文本?

javascript - 简单的 React 组件不渲染