【问题标题】:add a incremental counter using react app ++ operators not working使用 react app ++ 运算符添加增量计数器不起作用
【发布时间】:2020-07-14 18:02:04
【问题描述】:

我正在尝试编写每次用户单击按钮时进行投票的方法,它应该增加 1,它发生在下面的代码中

retro.js

  export class RetroComponent extends Component {
      constructor(props) {
        super(props);
        this.textareaRef = React.createRef();
        this.state = {
          value: 0
        }
      }
      addCard(){
        console.log("add card");
      }
      incrementWentWell() {
        // eslint-disable-next-line react/no-direct-mutation-state
        return ++this.state.value;
      }
    render() {
          return (
        <IconButton onClick={() => this.incrementWentWell()}>
                      <ThumbUpTwoToneIcon />
                    </IconButton>
       <h5 style={{marginRight: 10}}><p>{this.state.value}</p></h5>
    )}
    }

【问题讨论】:

标签: javascript reactjs increment


【解决方案1】:

仍然算作状态突变(巨大的反模式!)。忽略警告不会改变行为。使用功能状态更新来获取现有状态值,将其加 1,然后返回一个新状态对象,以便 react 可以协调更改并更新 UI/DOM。

incrementWentWell() {
  this.setState(state => ({ value: state.value + 1 })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2017-01-11
    • 1970-01-01
    • 2014-05-19
    • 2020-04-15
    • 2021-04-07
    • 2012-05-17
    相关资源
    最近更新 更多