我是reactjs的新手,我想在服务器中获取数据,以便它将向客户端发送包含数据的页面.
当函数getDefaultProps返回虚拟数据时,这是可以的,例如{data:{books:[{..},{..}]}}.
但是不能使用下面的代码.代码按此顺序执行,并显示错误消息"无法读取未定义的属性'书籍'
但是,我希望代码应按此顺序运行
任何的想法?
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>
})
} …Run Code Online (Sandbox Code Playgroud) 以下是我用来设置状态的代码.
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
if(!err){
this.setState( { quiz : value}); // ERROR: Cannot read property 'setState' of undefined
}
});
event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)
Rven虽然成功创建了数据库,但我无法调用this.state,因为它始终未定义.
我试过了:
self = this;
handleAddNewQuiz(event){
this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
if(!err){
self.setState( { quiz : value}); // ERROR: self.setState is not a function
}
});
event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)
但它仍然失败,尝试a = this和使用a.setState,仍然没有运气.
我怎么解决这个问题?
我试图在ajax回调从REST api接收数据后设置组件的状态.这是我的组件构造函数的代码
constructor(props) {
super(props);
this.state = { posts: [] };
this.getPosts = this.getPosts.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个componentDidMount看起来像下面的方法.
componentDidMount() {
this.getPosts();
}
Run Code Online (Sandbox Code Playgroud)
现在这是我的getPosts函数,我正在执行ajax请求.
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
this.setState( { posts: data } )
}
});
}
Run Code Online (Sandbox Code Playgroud)
我想要设置状态,但我收到以下错误.
this.setState is not a function
Run Code Online (Sandbox Code Playgroud)
不确定是什么导致了这一点.如果有人指出我正确的方向,那将是非常有帮助的.提前致谢.