Home > database >  How setState() can get 'state' without this in React class component
How setState() can get 'state' without this in React class component

Time:06-15

I am a student who started studying React. While studying about class components, I have a question. I have a question from this.setState inside the click() function of the source code below. 'this.setState' can get a state which is parameter in arrow function. How can 'setState' just get the previous state? I wonder how it is possible to get it with just state, not this.state. I guess it is related to the inherited React.Component class, but I would appreciate it if you could give me an accurate answer.

class Component extends React.Component {
        state = {
          count: 0,
        };

        constructor(props) {
          super(props);
          this.click = this.click.bind(this);
        }

        click() {
          this.setState((state) => ({ state, ...{ count: state.count   1 } }));
          console.log(this.state);
        }

        render() {
          return (
            <div>
              <button onClick={this.click}>click!</button>
              {this.state.count}
              {this.props.message}
            </div>
          );
        }
      }

      ReactDOM.render(<Component message='기본값 아니지롱' />, document.querySelector('#root'));

CodePudding user response:

You have to use this.state since state is a property of your class and not a standalone variable.

setState can access state since you declare that variable at the start of your arrow function. you could also call it banana. the first parameter of the arrow function gets filled with this.state.

CodePudding user response:

The state inside the callback function of this.setState is already the previous state, which is more accurate than this.state.

You could rename the parameter inside the callback whatever you want:

this.setState((prev)=>{ prev, ...{ count: prev.count   1 } }); // This works even better, since the prev here does not equal to this.state and more accurate

For details you could refer to this link

state (in the function above) is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props.

  • Related