使用 React 将状态值加一

新手上路,请多包涵

在 React 中,我试图让按钮增加一个存储在状态中的值。但是,使用下面的代码函数我的值在使用 handleClick 时设置为 undefined 或 NaN。

 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

原文由 dwigt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 929
2 个回答

因为您错误地使用了 handleClick 函数。这里:

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

prevState 将是一个传递给handleClick函数的事件对象,你需要使用prevState和setState,像这样:

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

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

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

检查工作解决方案:

 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>

原文由 Mayank Shukla 发布,翻译遵循 CC BY-SA 3.0 许可协议

你好,试试这些代码来增加你的价值

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

addOne() {                              // addOne as HandleClick
  this.setState((preState) => {
    return {
      count : preState.count + 1
      };
   });
 }

render() {
   return (
      <div>
        <h1>Count : {this.state.count}</h1>
        <button onClick={this.addOne}>+1</button>
      </div>
     );
   }
 }

ReactDOM.render(<Counter />, document.getElementById('YOUR-ID'));

原文由 user8290176 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进