javascript - 状态中的计数值不递增

标签 javascript reactjs react-hooks

在我的应用中,

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      count:0
    }
  }
  render() {
    return (
      <div className='App-header'>
        <button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>
      </div>
    )
  }
}

我在这个按钮上添加了一个事件:

<button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>

但是当我点击它时,count 的值没有增加

ps:我是新手

最佳答案

与 react 和状态管理相比,这更多地与普通的旧 javascript 有关。

以下是您的问题的小复制:

let y = 2;
y = y++;
console.log(y);
y = ++y;
console.log(y);

这是因为 ++ [(increment operator)](如果使用后缀,运算符在操作数之后(例如,x++),increment operator 递增并返回递增前的值。 ) 有效。

来自文档:

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

另外值得注意的是,你不应该做这样的事情:

this.state.variable = randomValue;

修复

this.setState({count:this.state.count=++this.state.count})

会工作因为

this.state.count=++this.state.count

返回增量计数。但是状态实际上是由 this.setState 更新的,你也可以这样做:

this.setState({count:++this.state.count})

When new state value is dependent on previous value

关于javascript - 状态中的计数值不递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72744313/

相关文章:

javascript - 使用 JavaScript 中对象的值获取键?

javascript - 在 Firefox WebExtension 中使用 OAuth 2.0

javascript - jQuery:滚动时更改页码的CSS

javascript - 上传到 heroku 后,移动 @media 查询不起作用

reactjs - 在拖放过程中,如果任何组件悬停在当前组件上,当前组件会更改其样式。这没有按预期发生吗?

javascript - 从自定义 react 钩子(Hook)返回函数数组?

javascript - 用于搜索用户评论 html styler 脚本的术语

javascript - 传递对象时防止在 PureComponent 上重新渲染

javascript - 如何在 React 渲染之前触发 useEffect?

reactjs - usePagination 自定义 Hook 与 material-ui 使用分页组件中的 next 和 prev 函数作为 Prop