2016-07-03 6 views
0

정기적으로 업데이트되는 구성 요소가 있는데이 구성 요소 외부에서 유틸리티 함수를 작성하려고합니다. 구성 요소가 업데이트 될 때 내부 상태를 업데이트해야합니다. 예를 들어React 구성 요소가 업데이트되었는지 확인하는 방법은 무엇입니까?

: 나는 Sample 기능에 Utility 기능을 통과해야한다면 나는이 달성 될 수있어

class Sample extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { counter: 1 }; 
    } 
} 

class Utility { 
    constructor(componentInstance) { 
    this.internalNum = // computedInstance's internal counter state (how?) 
    // and when the component has updated, I'd like to change the internalNum (how?) 
    } 
} 

SampleUtility 업데이트의 반작용 수명주기 방법을 기반으로,하지만 난 싶지 않아 그 종류의 종속성을 Sample에 소개합니다.

아마도 여기에는 더 좋은 디자인 패턴이 있습니다. 또는 이것이 괜찮 으면 어떻게 작동할까요?

+0

'샘플'의 여러 인스턴스를 렌더링하면 어떻게됩니까? –

답변

0

아마도

는 기본적으로는 사실에 후크가 여기에 더 나은 디자인 패턴이 새로운 값 Sample 전화 setState 그. 이러한 일은 (콜백 또는 이벤트로서) Sample에 의해 가장 잘 드러납니다.

또는 Sample 외부의 상태를 전체 장소로 이동할 수 있습니다. 예 : redux을 사용하십시오.

https://github.com/reactjs/redux

0

나는 당신이 (이 바위 때문에) 당신은 항상 REDUX를 구현해야해서 REDUX를 구현해야 @basarat에 동의합니다. 어쨌든 정적 속성을 사용하여이 시나리오에서 해결 방법을 만들 수 있습니다.

var _counter; 

class Sample extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { counter: 1 }; 
    _counter = 1; 
    } 

    updateCounter() { 
    var newCounter = this.state.counter + 1 

    this.setState({ counter: newCounter }); 
    _counter = newCounter; 
    } 

    static get counter() { return _counter; } 
} 

class Utility { 
    constructor(componentInstance) { 
    this.internalNum = Sample.counter; 
    } 
} 
관련 문제