javascript - Reactjs 组件 `this.state` 未定义

标签 javascript reactjs

我是 reactjs 的新手,并尝试制作一个组件。我在 componentWillMount() 中设置了 this.state,然后我调用了一个方法:

componentWillMount() {
        this.setState({ value: this.props.value || "0" });
        this.changeCbState = this.changeCbState.bind(this); 
        this.changeCbState();
    }

但是在我的方法中 changeCBState this.state 是未定义的:

changeCbState() {
        console.log(this.state.value)
    }

错误:Uncaught TypeError: Cannot read property 'value' of null

最佳答案

问题可能是您不会在构造函数中初始化状态,并且由于 this.setState 是异步的,因此在您尝试访问 changeCbState 之前可能不会初始化状态功能。

还有你在componentWillMount中编写的初始化代码lifecycle需要进去constructorcomponentWillMount方法应该被弃用。

constructor(props) {
    super(props);
        this.state = {
           value: this.props.value || "0"
        }
        this.changeCbState = this.changeCbState.bind(this); 
        this.changeCbState();
    }

关于javascript - Reactjs 组件 `this.state` 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51836941/

相关文章:

javascript - 我无法在 react 中更新我的数组状态?

twitter-bootstrap - Bootstrap 4 卡没有响应,它只是将其对齐为 1 直行

css - 如何调整胜率?

css - React Routes - body css 标签上的不同样式

javascript - 使用 AJAX 发送隐藏的 ID 输入字段

javascript - 跨域问题阻止我的 ajax 调用从我的 Express 文件中检索数据

javascript - 在组件的单​​独文件中使用 React hook

javascript - 有条件地在 Gatsby 中导入组件以获得非常动态的模板

Javascript 窗口未定义

javascript - 是否可以将对象转换为 Flow 中的精确类型?