我根据反应网站上的RSS
示例构建CommentBox
读者。
尝试将Google Feed API中的结果保存到状态时,状态未在jQuery ajax函数之外成功保存,我可以将变量读出到console.log
,结果信息正确无误但是当我读出函数之外的状态时,它打印出空数组,这是在首次调用组件时启动的。
var RSSApp = React.createClass({
getInitialState: function () {
return {feed:[]};
},
componentDidMount: function () {
this.loadRssFeed();
},
loadRssFeed: function() {
$.ajax({
url: 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=-1&q=' + encodeURIComponent(this.props.url),
dataType: "jsonp",
jsonCallback: "reponseData",
success: function(feed) {
var feeds = feed.responseData.feed.entries;
console.log(feeds)
console.log(feed.responseData.feed)
this.setState({feeds:feed});
}.bind(this)
});
console.log(this.state)
},
render: function () {
return (
<div className="RSSBox">
<h1>RSS Feed built using ReactJS</h1>
<RSSForm />
<RSSList data={this.state.feed} />
</div>
)
}
});
我在保存状态时出错了什么?
答案 0 :(得分:1)
您的代码存在的问题是您在设置之前尝试访问该状态。
$.ajax
调用是异步和非阻塞的,这意味着在从服务器实际返回数据之前执行console.log(this.state)
。为了修复此更改,您的代码看起来像这样(我添加了一些可能有用的注释):
var RSSApp = React.createClass({
getInitialState: function () {
return {feed:[]};
},
componentDidMount: function () {
this.loadRssFeed();
},
loadRssFeed: function() {
$.ajax({
url: 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=-1&q=' + encodeURIComponent(this.props.url),
dataType: "jsonp",
jsonCallback: "reponseData",
success: function(feed) {
// the success callback is executed asynchronously after some time (time required to get the data from server)
var feeds = feed.responseData.feed.entries;
console.log(feeds)
console.log(feed.responseData.feed)
this.setState({feeds:feed});
console.log(this.state); // <-- this should work, continue with state manipulation here
}.bind(this)
});
// console.log(this.state) -- this will be executed before the data is returned from the server as previous call $.ajax is non-blocking
},
render: function () {
return (
<div className="RSSBox">
<h1>RSS Feed built using ReactJS</h1>
<RSSForm />
<RSSList data={this.state.feed} />
</div>
)
}