2017-11-18 287 views
0

我正在嘗試使用react-native進行auth註銷,並且遇到了要重置redux存儲庫的狀態的問題,但是,因爲我正在使用react-navigation,所以我有一堆使用了redux的連接當狀態樹重置爲初始狀態時會導致一堆異常錯誤,仍然安裝的屏幕會重新渲染。我嘗試通過用戶重定向到註冊/登錄屏幕的react-navigation重置進行註銷來卸載它們,但我無法知道這些屏幕何時被實際卸載以便調用RESET_STATE操作。最初,我正在通過傳奇發送行動。如何在react-navigation重置不立即從堆棧中卸載屏幕時使用react-navigation來重置redux store的狀態?

傳奇/ logout.js

import { LOGOUT, RESET_STATE } from 'Actions/user'; 
 

 
// clear localstorage once user logs out. 
 
const clearData = function* clearData(action) { 
 
    AsyncStorage.removeItem('user'); 
 
    
 
    yield put(
 
    NavigationActions.reset({ 
 
     index: 0, 
 
     actions: [ 
 
     NavigationActions.navigate({ routeName: 'SignedOut' }) 
 
     ], 
 
    }) 
 
); 
 
    // causes re-renders, screens still mounted 
 
    yield put({type: RESET_STATE}); 
 
} 
 

 
export default function* logoutSaga() { 
 
    yield all([ 
 
    yield takeEvery(LOGOUT, clearData), 
 
    ]); 
 
}

我也試過一次的用戶達到SignedOut屏幕在它的componentDidMount週期,但componentDidMount後遺憾的是屏幕在某些時候卸載以及重置被觸發:

screens/SignedOut.js

import { resetState } from 'Actions/user'; 
 
import ActionButton from 'Components/FormElements/ActionButton'; 
 

 
class SignedOut extends Component { 
 
    // screens are still mounted, causing screens from 
 
    // previous screens to throw exception errors 
 
    componentDidMount() { 
 
    this.props.dispatch(resetState()); 
 
    } 
 

 
    componentWillUnmount() { 
 
    // never called 
 
    } 
 

 
    handleSignup =() => { 
 
    this.props.navigation.navigate('Signup'); 
 
    } 
 

 
    handleLogin =() => { 
 
    this.props.navigation.navigate('Login'); 
 
    } 
 

 
    render() { 
 
    return(
 
     <Container> 
 
     <ActionButton 
 
      text="Sign Up" 
 
      handleButtonPress={this.handleSignup} 
 
     /> 
 
     <ActionButton 
 
      text="Log In" 
 
      handleButtonPress={this.handleLogin} 
 
     /> 
 
     </Container> 
 
    ); 
 
    } 
 
} 
 

 
export default connect()(SignedOut);

我的問題是,任何人都可以想辦法畢竟我的屏幕終於由反應導航復位動作卸載重置Redux的商店狀態?

回答

0

問題在於,您正在使用導航導航到登錄/註冊屏幕,導致所有其他組件都掛載,您應該使用返回或重置來卸載所有組件並顯示登錄屏幕。

+0

我正在使用重置,問題是它不會立即卸載所有的屏幕,它發生在重置導致的重定向完成後。 – eballeste

0

因爲我不知道你的狀態是怎麼樣的,在這裏總是有問題,爲什麼不嘗試在所有這些組件上使用componentWillUnmount,設置一個狀態變量並檢查當你想重置導航?

0

經過很長一段時間的思考之後,我發現可能我應該專注於拋出的錯誤,而不是爲什麼我會出錯。 (雖然我確實學到了很多東西)。

儘管在調用重置後所有屏幕完全卸載時如何偵聽如何偵聽會非常有用,但它只是一種繞過實際問題的快捷方式,我的redux狀態的某些分支的initialState錯了。無論何時反應導航決定卸載舊屏幕,糾正此錯誤之後都不會出現更多錯誤。