2016-06-27 2 views
4

나는 componentDidMount()에 생성하고있는 변수를 가지고 있는데 componentDidUpdate()에서 사용할 수 있기를 바랍니다. 이견있는 사람? 코드는 다음과 같습니다.componentDidMount에서 작성한 액세스 변수

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

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

    render() {...} 
} 

답변

8

구성 요소에 저장하십시오. @Gosha Arinich이 유용하게 그것을 지적

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

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

또한, - 그것이 가장에 배치됩니다 - 당신은 구성 요소의 라이프 사이클이 변수를 사용 다시하고 업데이트 및/또는 렌더링 할 계획 않는 경우 알고 있어야 성분 (this.state)의 state.

+1

오 세상에 내가 할 수 있다는 생각이 전혀 들지 않았다. 그건 훌륭합니다! 고맙습니다! – jasonetco

+1

@jasonetco 도와 드리겠습니다. 'this'의 사용법을 꼭 읽어보십시오. Javascript의 더 어려운 개념 중 하나입니다. 좋은 관련 질문 및 여러 답변을 찾을 수 있습니다 [여기] (http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –

+1

또한이 값을 갈 경우 염두에 두십시오 컴포넌트 라이프 사이클 동안 업데이트되어야하고,'render'에서 사용된다면, 그것을 상태로 넣는 것이 낫습니다. –