在componentDidMount中创建的访问变量

时间:2016-06-27 16:41:53

标签: javascript reactjs scope

我有一个我在i + j创建的变量,我希望它可以在componentDidMount()中使用。有什么想法吗?代码如下所示:

componentDidUpdate()

1 个答案:

答案 0 :(得分:17)

然后将其保存到组件中。

componentDidMount() {
    this.myVariable = 'this thing';
}

componentDidUpdate() {
    // I'd like my variable to be accessible here
    console.log(this.myVariable);
}

另外,正如@Gosha Arinich所指出的那样 - 请注意,如果您计划在整个组件的生命周期中重复使用此变量并更新和/或呈现它 - 最好放入{{1}组件(state)。

相关问题