Incrementing state value by one using React

后端 未结 8 1921
不知归路
不知归路 2021-01-30 17:33

In React I am trying to make a button increment a value stored in state. However using the code below function my value is set undefined or NaN when using handleClick.

8条回答
  •  野性不改
    2021-01-30 18:27

    You can do it this way also where we do both increment and decrement operation with same function making it more modular and redable

    class CounterApp extends React.Component{
    
        constructor(){
            super();
            //here count is initially assigned with 0
            this.state ={
            count:0
            }
        }
        
        //when we click Increment or Decrement +1 or -1 is passed to step and the value gets changed it gets updated to the view
        increment = (step) =>{
            this.setState({
                count:this.state.count + step
            })
        }
        render(){
            const { count } = this.state;//same as const count = this.state.count;
    
            return(
                

    {count}

    ) } }

提交回复
热议问题