如何更新有对象的反应状态?

Ple*_*air -2 reactjs

我有反应的状态,其中包括称为增量的对象。在该对象内部,我有一个名为count的属性,其值为0。有人知道如何通过单击按钮来增加count的值吗?

import React, { Component } from 'react';


class App extends Component {
  constructor(){
    super();

    this.state = {
      increment:{
        count:0
      }
    }

    this.handleClick = this.handleClick.bind(this)
  }


  handleClick() {

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


  render() {

    return (
      <div>
          <h1>{this.state.increment.count}</h1>
          <button onClick={this.handleClick}>Change!</button>

      </div>
    )
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

React给我一个错误,称为解析错误:意外的令牌,预期为“,”

Ami*_*han 6

您更新状态的语法是错误的。您不能将键添加为crement.count。这是正确的语法。

handleClick() {

    this.setState(prevState => {
       return {
           increment: {
               count: prevState.increment.count + 1
           }
       }
    })
}
Run Code Online (Sandbox Code Playgroud)