I need to change state by clicking. I have this code:

 var Component = React.createClass({ getInitialState : function() { return {value : 0} } changeState : function(event) { this.setState({value : event.target.id}) ; } render : function() { <a id="1" onClick={this.changeState}>Change</a> } }) ; 

But the change only works after the first click, the first click I get 0 , the second click, I get 1 .

I reread the dock where it is said not to use setState directly, so I used replaceState , but it still returns the previous value. How to deal with it?

  • How do you check the status of a component? - Dmitriy Simushev
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • one
    This code does not work at all, return there is no return . And I propose to add a viable snippet to the question. And yet, I didn’t see a recommendation in the dock not to use setState - you definitely don’t confuse with a recommendation not to use state for writing? - Qwertiy

2 answers 2

SetState has a rather rarely mentioned second parameter, which is an ordinary callback function. You can catch the new state of the component already there this.setState({/* new state */}, callback) .

 var Component = React.createClass({ getInitialState : function() { return {value : 0} } changeState : function(event) { this.setState({value : event.target.id}, function() { /* Получаем измененное значение state */ console.log(this.state.value); }) ; } render : function() { return <a id="1" onClick={this.changeState}>Change</a> } }) ; 

Or we form a new state object, and only then we write it down:

 var Component = React.createClass({ getInitialState : function() { return {value : 0} } changeState : function(event) { /* формируем новый state */ let nextState = Object.assign({}, this.state, { value: event.target.id }); /* получаем будущее значение state */ console.log(nextState.value); /* записываем новый state */ this.setState(newState); } render : function() { return <a id="1" onClick={this.changeState}>Change</a> } }) ; 

Recently did a small translation about the work of state . Perhaps useful

  • It would be possible to spend a little excerpt from the article. - AivanF.
  • With pleasure :-) - Anton K.

Apparently, you are faced with the fact that the value of this.state does not change immediately after calling this.setState() . At the same time, this behavior is regular (see the documentation ):

setState () doesn’t immediately mutate this.state but creates a pending state transition. Accessing this.state after this value.

I have a feeling that you are misusing the state of a component. Unfortunately, without a normal description of the original problem, it is pointless to give any advice.