[英]setState in react is not working in react component
I'm trying to create a small react component, however, I am unable to set the state. 我正在尝试创建一个小的react组件,但是无法设置状态。 Below is my code.
下面是我的代码。 In the
_onChange
function, I am trying to set an array of length 10 to State and console.log
the same. 在
_onChange
函数中,我试图将长度为10的数组设置为State和console.log
相同。 I am getting an empty array in the console. 我在控制台中得到一个空数组。
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> ) } });
setState
is asynchronous. setState
是异步的。 The value will not be set immediately. 该值将不会立即设置。 You can pass a callback to
setState
which will be called when new state is set. 您可以将回调传递给
setState
,在设置新状态时将调用该回调。
From react documentation https://facebook.github.io/react/docs/component-api.html 从反应文档https://facebook.github.io/react/docs/component-api.html
setState()
does not immediately mutate this.state but creates a pending state transition.setState()
不会立即使this.state发生突变,但会创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value.调用此方法后访问this.state可能会返回现有值。
You can change your code 您可以更改代码
this.setState({reviewData: ReviewStore.getRating()}, function () {
console.log(this.state.reviewData)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.