setState in react is not working in react component

reactjs state setstate

2048 просмотра

1 ответ

I'm trying to create a small react component, however, I am unable to set the state. 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. 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>
        )
    }
});

Автор: Chaitu Источник Размещён: 08.11.2019 10:55

Ответы (1)


4 плюса

setState is asynchronous. The value will not be set immediately. You can pass a callback to setState which will be called when new state is set.

From react documentation https://facebook.github.io/react/docs/component-api.html

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

You can change your code

this.setState({reviewData: ReviewStore.getRating()}, function () {
    console.log(this.state.reviewData)
});
Автор: Michał Размещён: 20.08.2016 05:51
Вопросы из категории :
32x32