在componentDidMount中创建的访问变量

jas*_*tco 9 javascript scope reactjs

我有一个我正在创建的变量,我componentDidMount()希望它可用componentDidUpdate().有什么想法吗?代码如下所示:

class Example extends Component {
  componentDidMount() {
    const myVariable = 'this thing';
  }

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

  render() {...}
}
Run Code Online (Sandbox Code Playgroud)

Elo*_*pos 23

然后将其保存到组件中.

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

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

此外,正如@Gosha Arinich所指出的那样 - 请注意,如果您计划在整个组件的生命周期中重复使用此变量并更新它和/或进行渲染,则最好将其置于state组件(this.state)中.

  • 哦,天哪,我不知道你能做到这一点......那太棒了!谢谢! (2认同)
  • @jasonetco乐于助人.请务必阅读"this"的用法.这是Javascript中难以掌握的概念之一.可以找到一个好的相关问题和多个答案[这里](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) (2认同)