【问题标题】:Access variable made in componentDidMount在 componentDidMount 中创建的访问变量
【发布时间】:2016-10-29 18:32:00
【问题描述】:

我在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() {...}
}

【问题讨论】:

    标签: javascript reactjs scope


    【解决方案1】:

    然后将其保存到组件中。

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

    另外,正如@Gosha Arinich 有用地指出的那样 - 请注意,如果您确实计划在整个组件的生命周期中重复使用此变量并更新和/或渲染它 - 最好将其放入 state 的组件 (this.state)。

    【讨论】:

    • 天哪,我不知道你能做到这一点……太棒了!谢谢!
    • @jasonetco 很高兴为您提供帮助。确保您阅读了this 的用法。它是 Javascript 中较难掌握的概念之一。一个很好的相关问题和多个答案可以找到here
    • 另外请记住,如果这个值要在组件生命周期中更新,并且如果在render中使用,最好将其放入状态。
    • @GoshaArinich 我明白了,但在这种情况下,我不需要更新它,只需使用该值。除此之外,据我了解,在componentDidMount() 中使用setState() 是个坏主意
    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多