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
相关产品推荐
相关产品推荐

