생각은 길게 코딩은 짧게

[React-Native] 이전 페이지 리렌더링 본문

React Native

[React-Native] 이전 페이지 리렌더링

sayhee 2023. 4. 12. 18:05
728x90

비밀번호 변경 후 재로그인을 위해 다시 로그인 창을 불러야하는 경우가 생겼다.

React Native에서 page를 navigate하는 것은(this.props.navigation.navigate('Login'))
stack 구조로 진행이 되기 때문에 이미 didMount된 상태의 페이지가 불러져
다시 componentDidMount가 실행 되지 않는다.


해결 전

해결 후

해결 전 문제점 : componentDidMount가 다시 실행되지 않아 이미 로그인 되어있는 창이 불러졌다

 

 

💡 this.props.navigation.addListener() 사용

react navigation 공식문서
stack overflow에서 참고

componentWillUnmount 는 컴포넌트가 화면에서 사라지기 직전에 호출된다.

정보 수정 창이 화면에서 사라질 때 login 창이 포커스 되면 addListener 함수를 호출하여 로그인 창을

리렌더링 할 수 있을 것 같다 그래서 바로 addListener 함수를 프로젝트에 적용시켜보았다!

 

 

✔️ 내정보 수정창에서 수정완료 버튼을 눌렀을 경우 Login 창으로 navigate

 //수정완료 버튼을 눌렀을 때
    goImageUpload = () => {
        this.callModifyUserAPI().then((response) => {
            console.log('response message =', response);
            if (this.state.passwd !== this.state.passwordok)
                this.setState({ passwderror: true })
            else if (this.state.passwd == this.state.passwordok) {
                this.setState({ passwderror: false })
                if (response.success == 1) {
                    AsyncStorage.clear();
                    Alert.alert('정보 수정이 완료되었습니다', '로그인 창에서 재로그인 해주세요', [
                        { text: '확인', onPress: () => { this.props.navigation.navigate("Login") } },
                    ]);
                }
                else {
                    Alert.alert('정보 수정을 실패하였습니다.');
                }
            }
        })
    }

 

✔️ focusListener를 통해 로그인 창이 'focus' 되었을 때 유효성 검사 함수를 실행하고 state값을 변경

//자동로그인
componentDidMount() {
    this.focusListener = this.props.navigation.addListener('focus', () => {
        //when Login Screen focus
        this.onValueChange();
        this.setState({companyNo:"",passwd:"",autoLoginChecked: false,rememberIdChecked: false}) 
    })
}
componentWillUnmount () {
    this.focusListener()
}