Reactjs 在呈现之前在服务器中响应获取数据
我是reactjs新手,我想在服务器中获取数据,以便它将包含数据的页面发送到客户端 当函数getDefaultProps返回如下{data:{books:[{..},{..}]}的伪数据时,这是正常的 但是,不能使用下面的代码。代码按此顺序执行,错误消息为“无法读取未定义的属性'books'”Reactjs 在呈现之前在服务器中响应获取数据,reactjs,Reactjs,我是reactjs新手,我想在服务器中获取数据,以便它将包含数据的页面发送到客户端 当函数getDefaultProps返回如下{data:{books:[{..},{..}]}的伪数据时,这是正常的 但是,不能使用下面的代码。代码按此顺序执行,错误消息为“无法读取未定义的属性'books'” getDefaultProps 返回 取回 {数据:{书籍:[{..},{..}]} 但是,我希望代码应该按照这个顺序运行 getDefaultProps 取回 {数据:{书籍:[{..},{..}]}
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>
);
}
静力学:{
fetchData:函数(回调){
var me=这个;
超级药剂,快去http://localhost:3100/api/books')
.accept('json')
.end(函数(err、res){
如果(错误)抛出错误;
var data={data:{books:res.body}
log('fetch');
回调(数据);
});
}
getDefaultProps:function(){
log('getDefaultProps');
var me=这个;
me.data='';
this.fetchData(函数(数据){
log('callback');
控制台日志(数据);
me.data=数据;
});
console.log('return');
返回我的数据;
},
render:function(){
console.log('render book list');
返回(
{
this.props.data.books.map(函数(书){
return- {book.name}
})
}
);
}
在React中,道具
用于组件参数,而不是用于处理数据。有一个单独的结构称为状态
。每当更新状态
时,组件基本上会根据新值重新呈现自身
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>
);
}
});
var BookList=React.createClass({
//从服务器获取图书列表
getBookList:函数(){
超级药剂,快去http://localhost:3100/api/books')
.accept('json')
.end(函数(err、res){
如果(错误)抛出错误;
这是一个稳定的状态(res);
});
},
//用于更新组件状态的自定义函数
setBookListState:函数(书本){
这是我的国家({
书:书。数据
});
},
//React公开此函数以允许您设置默认状态
//您的组件的
getInitialState:函数(){
返回{
书籍:[]
};
},
//React公开此函数,您可以将其视为
//组件的构造函数。在此处调用数据。
componentDidMount:function(){
这是.getBookList();
},
render:function(){
var books=this.state.books.map(函数(book)){
返回(
{book.name}
);
});
返回(
{books}
);
}
});
您要查找的是组件将挂载
从:
在客户端和服务器上调用一次,在
初始呈现发生。如果在此方法中调用setState
,
render()
将看到更新的状态,并且只执行一次
尽管国家发生了变化
所以你可以这样做:
componentWillMount : function () {
var data = this.getData();
this.setState({data : data});
},
这样,
render()
将只被调用一次,您将在初始渲染中获得所需的数据。回答了一个类似的问题,并给出了一个可能的简单解决方案。如果有人仍在寻找答案,关键是它涉及到使用redux sagas:
或者直接跳到我写的关于这个主题的文章:
作为Michael Parker答案的补充,您可以让getData接受回调函数以激活setState更新数据:
componentWillMount : function () {
var data = this.getData(()=>this.setState({data : data}));
},
我用来从服务器接收数据并显示数据的最佳答案
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}/>
}
) }
构造函数(道具){
超级(道具);
此.state={
项目2:[{}],
孤岛加载:正确
}
}
组件将安装(){
axios({
方法:“get”,
responseType:'json',
网址:‘……’,
})
。然后(响应=>{
自我状态({
项目2:答复,
孤岛加载:false
});
log(“Asmaa Almadhoun***:”+self.state.items2);
})
.catch(错误=>{
console.log(“错误***:”+错误);
});
})}
render(){
返回(
{this.state.isLoading&&
}
{!正在加载此.state.isLoading&&
//将服务器数据传递给其类的外部组件
}
) }
这是一个非常简单的示例
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>
);
}
}
import React,{Component}来自'React';
从“react native”导入{View,Text};
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:空
};
}
组件willmount(){
这个.renderMyData();
}
renderMyData(){
取('https://your url')
.then((response)=>response.json())
.然后((responseJson)=>{
this.setState({data:responseJson})
})
.catch((错误)=>{
控制台错误(error);
});
}
render(){
返回(
{this.state.data?:}
);
}
}
在尝试渲染之前,您可以使用包在服务器上预取数据我也偶然发现了这个问题,学习了React,并通过显示微调器解决了它,直到数据准备就绪
render() {
if (this.state.data === null) {
return (
<div className="MyView">
<Spinner/>
</div>
);
}
else {
return(
<div className="MyView">
<ReactJson src={this.state.data}/>
</div>
);
}
}
render(){
if(this.state.data==null){
返回(
);
}
否则{
复述