2017-11-17 10 views
1

나는 MobX를 React Native에서 사용하고 있으며, 지금까지는 정말 라이트 업하고 있습니다. Mobx Store의 상태가 변경되면 함수를 호출하는 라이프 사이클이나 메소드가 있습니까?React Native, MobX and lifecycle

+0

넌 mobx [반응]를 사용하여 (https://mobx.js.org을 /refguide/reaction.html) 메소드 –

답변

1

componentWillReceiveProps은 구성 요소 수준에서 사용할 수 있습니다. 당신이 notificationStore.message 예를 변이 할 때, 이제

class Notification extends PureComponent<Props> { 
    ... 
    public componentWillReceiveProps(nextProps: any): void { 
    Alert.alert('message', nextProps.message); 
    } 
} 

:

@inject('notificationStore') 
@observer 
class SomeContainer extends Component<Props> { 
    ... 

    public render(): JSX.Element { 
    <Notification 
     message={this.props.notificationStore.message} 
     ... 
    /> 
    } 
} 

및 알림에 : 예를 들어, 관찰자 ​​컨테이너는 소품을 통해 실제 구성 요소 (타이프에서 가상의 사용 사례를) 통지합니다. 'Hello world' 알림 구성 요소에 의해 표시됩니다.

직접 접근 방식을 원한다면 구성 요소를 저장소에 주입하고 변경 사항을 관찰하십시오. 기본적으로 당신의 타이프 라이터 인터페이스는 다음과 같이한다 : 당신이 볼 수 있듯이, 저장소가 항상 소품으로 간주되고

interface Props { 
    notificationStore?: any; 
    ... 
} 

이 돌연변이가 componentWillReceiveProps 라이프 사이클 이벤트를 트리거 것을 의미합니다.

희망 사항을 충분히 설명했습니다.

0

componentWillUnmountcomponentDidMountautorun에 넣고이를 폐기 할 수

예 (JSBin)

const store = observable({ 
    data: "data" 
}); 

setTimeout(() => { 
    store.data += " updated!"; 
}, 2000); 

@observer 
class App extends Component { 
    componentDidMount() { 
    this.disposer = autorun(() => { 
     console.log(`Data changed: ${this.props.store.data}`); 
    }); 
    } 

    componentWillUnmount() { 
    this.disposer(); 
    } 

    render() { 
    return <h1>{this.props.store.data}</h1>; 
    } 
}; 

ReactDOM.render(
    <App store={store} />, 
    document.getElementById("app") 
);