You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件state为undefined、点击按钮修改state不生效问题求助

问题点说明
  • 类组件的state属性必须通过this.state.属性名的方式读取,你代码中所有直接写this.displayCancel的写法都是错误的,相当于访问实例上不存在的属性,自然返回undefined。
  • setState是异步更新接口,调用后不会立刻修改当前上下文的this.state值,如需拿到更新后的state,可使用setState的第二个回调参数,回调会在state更新完成、视图重渲染后触发。
修正后可运行的完整代码
import React, { Component } from 'react';

class ClassBasedComponent extends Component {
  constructor(){
    super();     
    this.state = {
      displayCancel: true
    };
    this.cancelRequest = this.cancelRequest.bind(this);
  } 

  // 取消请求方法
  cancelRequest() {
    this.setState(
      { displayCancel: false },
      // 回调函数:state更新完成后执行
      () => console.log(this.state.displayCancel)
    );
  }

  render() { 
    return (
      <>
        <button onClick={this.cancelRequest}>Cancel</button>
        {this.state.displayCancel ? <>Hi</> : <>bye</>}
      </>
    )
  }
}

export default ClassBasedComponent;

内容的提问来源于stack exchange,提问作者Rajendra Bar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:09:03