我正在尝试创建一个小的反应组件,但是,我无法设置状态。下面是我的代码。在_onChange
函数中,我试图将一个长度为 10 的数组设置为 State 和console.log
相同的值。我在控制台中得到一个空数组。
var Home = React.createClass({
getInitialState: function () {
return ({
reviewData: []
});
},
componentWillMount: function() {
ReviewStore.addChangeListener(this._onChange);
ReviewAction.getRatings();
console.log(this.state.reviewData);
},
_onChange: function() {
var res = ReviewStore.getRating();
console.log(res); //Here I am getting array of length 10
this.setState({reviewData: ReviewStore.getRating()});
console.log(this.state.reviewData); //Here I am getting array of length 0
},
componentWillUnmount: function () {
ReviewStore.removeChangeListener(this._onChange);
},
ratingChanged : function(newRating) {
console.log(newRating)
},
render: function() {
return(
<div>
<h2>Rating of Arlo Smart Home 1 HD Camera</h2>
<hr/>
<h4>Average Rating: </h4><ReactStars half={false} onChange={this.ratingChanged} size={24}/>
</div>
)
}
});