gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:57:57 25 4
gpt4 key购买 nike

我是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com