0

As I am learning react at the moment I came across this concept of event handler using "setState".

It is a little complicated for my understanding as 3 functions within each other. Case in point.

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };

this.increment = this.increment.bind(this)
    
increment(){
    this.setState(state => ({count: state.count+ 1}))
} 

//....some other code

This code works. I tried to understand the increment function a little further but I can't understand why the following code will not work:

increment(){
  this.setState(function anon(state){
    count: state.count+1
    })
}

What is wrong with this code?

BitByBit
  • 523
  • 3
  • 13

2 Answers2

2
function anon(state) {
  count: state.count + 1
}

^ This function is neither creating an object, nor returning anything from the function. It is creating a label called count inside the function. So, it is not throwing a syntax error.

this.setState(state => ({ count: state.count+ 1 }))

^ This callback creates an object with count key and implicitly returns it. It is equivalent to the following code when you use a regular function

this.setState(function (state) => {
   return { count: state.count+ 1 }
})
adiga
  • 28,937
  • 7
  • 45
  • 66
0

The only missing part is return.

increment(){
  this.setState(function anon(state){
    return {count: state.count+1}
    })
}
Charlie
  • 18,636
  • 7
  • 49
  • 75