如何在react-navigation重置不立即从堆栈中卸载屏幕时使用react-navigation来重置redux store的状态?

如何在react-navigation重置不立即从堆栈中卸载屏幕时使用react-navigation来重置redux store的状态?

问题描述:

我正在尝试使用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

我正在使用重置,问题是它不会立即卸载所有的屏幕,它发生在重置导致的重定向完成后。 – eballeste

因为我不知道你的状态是怎么样的,在这里总是有问题,为什么不尝试在所有这些组件上使用componentWillUnmount,设置一个状态变量并检查当你想重置导航?

经过很长一段时间的思考之后,我发现可能我应该专注于抛出的错误,而不是为什么我会出错。 (虽然我确实学到了很多东西)。

尽管在调用重置后所有屏幕完全卸载时如何侦听如何侦听会非常有用,但它只是一种绕过实际问题的快捷方式,我的redux状态的某些分支的initialState错了。无论何时反应导航决定卸载旧屏幕,纠正此错误之后都不会出现更多错误。