尝试在反应中更新计数器的状态

Trying to update the state of the counter in react

已经有一段时间没有使用 React 了。刚刚回到它并试图更新状态。据我所知,我应该能够使用下面的方法更新状态。但是,它没有更新年龄的价值。我错过了什么吗?

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      age: 0
    }

    this.increaseAge = this.increaseAge.bind(this)
  }

  increaseAge=()=> {
    this.setState({
      age: this.state.age + 1
    })

    console.log("hi")
  }


  render() {
    return(
      <div className="app-content">
        <h1>Hey Ninjas</h1>
        <p>{this.state.age}</p>
        <button onClick={this.icreaseAge}>Increment</button>
      </div>
    );
  }
}

export default App;

你打错了,你错过了来自 increaseAge

的字母 (n)

现在应该可以了。

        <button onClick={this.increaseAge}>Increment</button>
<button onClick={this.icreaseAge}>Increment</button>

您在 onClick 中输入错误。否则它应该工作得很好。

<button onClick={this.increaseAge}>Increment</button>

作为旁注,您不应该像以前那样通过访问组件的 state 来更新您的 state,而是应该这样:

increaseAge = () => {
  this.setState((state) => ({ age: state.age + 1 }));
  // or shorter
  this.setState(({ age }) => ({ age: age + 1 }));
}

你的实施问题是由于 React 的状态更新是异步的并且可以批处理,所以你的 age 更新最终可能会 age 被其他 [=15] 覆盖=] 调用,然后最终更新不正确。

你可以看看documentation