Incrementing state value by one using React

后端 未结 8 1830
不知归路
不知归路 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

    set state is async so you wont see the value update when the console.log happens. You should have the state value printed out on the UI so you can see whats happening. To fix the console log try this.

    class QuestionList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {value: 0};
      }
    
       handleClick = (prevState) => {
        this.setState({value: prevState.value + 1}, () => {
            console.log(this.state.value)
        });
      }
    

    NOTE: when you define an inline lambda (arrow function) for a react class this is bound correctly so you dont need to bind it in the constructor.

    also you can change the way you pass the previous number if its just a state increment like this

    handleClick = () => {
        this.setState({value: this.state.value + 1}, () => {
            console.log(this.state.value)
        });
    }
    

提交回复
热议问题