React updateState function

React updateState function

本文关键字:function updateState React      更新时间:2023-09-26

我有一个简单的更新数据功能,目前不工作:

    class App extends React.Component {
           constructor(props) {
              super(props);
              this.state = {
                 data: 'Initial data...'
              }
              this.updateState = this.updateState.bind(this);
           };
           updateState() {
              this.setState({data: 'Data updated...'})
           }
           render() {
              return (
                 <div>
                    <button onClick = {this.updateState}>CLICK</button>
                    <h4>{this.data}</h4>
                 </div>
              );
           }
        }
   ReactDOM.render(<App/>, document.getElementById('app'));

下面是jsbin的链接:

http://jsbin.com/vidumiroki/edit?html、js、输出

您在返回渲染函数中错过了状态

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated...'})
   }
   render() {
      return (
         <div>
            <button onClick = {this.updateState}>CLICK</button>
            <h4>{this.state.data}</h4>
         </div>
      );
   }
}
ReactDOM.render(<App/>, document.getElementById('app'));