React.js值未在按钮上更新

问题描述 投票:0回答:3

Console.log打印增量值,但值未在按钮中更新

'use strict';

const e = React.createElement;

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

  render() {
    return e(
      'button',
      {
        onClick: () => {
          this.state.val = this.state.val + 1
          console.log(this.state.val)
        }
      },
      'Like' + this.state.val // here Like 1 should be displayed
    );
  }
}

const domContainer = document.querySelector('#root');
ReactDOM.render(e(Counter), domContainer);
reactjs
3个回答
1
投票

你必须使用setState来更新状态。和状态更新是异步调用,因此您必须使用回调函数来检查天气存储是否更新。

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

updateState(){
        this.setState({val : this.state.val + 1 }, function(){
            console.log(this.state.val)
        })
}

render() {
    return e(
    'button',
    {
        onClick: () => {this.updateState()
        }
    },
    'Like' + this.state.val
    );
}
}

3
投票

你永远不应该直接更新状态。始终使用setState

this.state.val = this.state.val + 1;  // bad
this.setState((state) => ({           // good
    val: state.val + 1
}))

否则React将不会“看到”更新,也不会重新渲染。


1
投票

您必须通过this.setState()函数更新React状态。否则,组件不会重新渲染。这是React的基础。您应该阅读更多React文档或做一些教程。

你可以阅读更多here

© www.soinside.com 2019 - 2024. All rights reserved.