使用React将状态值递增1

使用React将状态值递增1

本文介绍了使用React将状态值递增1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React中,我试图使按钮增加存储在state中的值.但是,使用下面的代码,使用handleClick时,我的值设置为undefined或NaN.

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.

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

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

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

您能告诉我为什么会这样吗?根据这里的文档,它应该是正确的: https://facebook.github.io/react/docs/state-and -lifecycle.html

Can you tell me why this is happening? it should be correct according to the docs here:https://facebook.github.io/react/docs/state-and-lifecycle.html

推荐答案

因为您使用的handleClick函数不正确.在这里:

Because you are using the handleClick function incorrectly. Here:

handleClick = (prevState) => { .... }

prevState将是传递给handleClick函数的事件对象,您需要将prevState与setState一起使用,如下所示:

prevState will be an event object passed to handleClick function, you need to use prevState with setState, like this:

handleClick = () => {
    this.setState(prevState => {
       return {count: prevState.count + 1}
    })
}

另一个问题是,setState是异步的,因此console.log(this.state.value)不会打印更新后的状态值,您需要对setState使用回调函数.

Another issue is, setState is async so console.log(this.state.value) will not print the updated state value, you need to use callback function with setState.

检查有关异步行为的更多详细信息setState 以及如何检查更新的值.

Check more details about async behaviour of setState and how to check updated value.

检查可行的解决方案:

class App extends React.Component {

   constructor(props){
       super(props);
       this.state={ count: 1}
   }

  onclick(type){
      this.setState(prevState => {
         return {count: type == 'add' ? prevState.count + 1: prevState.count - 1}
      });
  }

   render() {
    return (
      <div>
        Count: {this.state.count}
        <br/>
        <div style={{marginTop: '100px'}}/>
        <input type='button' onClick={this.onclick.bind(this, 'add')} value='Inc'/>
        <input type='button' onClick={this.onclick.bind(this, 'sub')} value='Dec'/>
       </div>
     )
   }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'></div>

这篇关于使用React将状态值递增1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:23