前段時間使用redux在react-native中,安卓後退兩次關閉後redux未清空的問題,一直以爲處理的不夠優雅,沒有根本解決問題。html
後來發現再退出登陸後,也有部分數據由於redux的邏輯處理數據緩存問題被留了下來,形成一些意料以外的問題,因而要完全解決重置redux的辦法。react
個人解決方法是,寫一個action用來處理退出登陸,每一個reducer都監聽這個type,return初始值。redux
//action export const LOGIN_OUT = 'LOGIN_OUT'; export const loginOut = () => { return { type: LOGIN_OUT } }
//reducer import * as User from '../actions/userAction'; const user = { type: 0, name: '', uid: '', phone: '' } export default (state = user, action) => { switch (action.type) { ...... case User.LOGIN_OUT: return user break; default: return state; } }
//其餘reducer import { LOGIN_OUT } from '../actions/userAction'; const finance = { ... } export default (state = finance, action) => { switch (action.type) { ...... case LOGIN_OUT: return finance break; default: return state; } }
//退出登陸時處理邏輯 export default connect( (state) => ({}), (dispatch) => ({ loginOut: () => { dispatch(loginOut()); Storage.remove({ key: 'user' }); resetRouter('Login'); } }) )(...)
//rn中後退2次邏輯處理 onBackAndroid = () => { const routers = this.navigator._navigation.state.routes; if (routers.length > 1) { this.navigator.pop(); return true; } else { if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) { Store.dispatch(loginOut());//redux重置 return false; } this.lastBackPressed = Date.now(); ToastAndroid.show('再按一次退出應用', ToastAndroid.SHORT); return true; } };
1 export const LOGIN_OUT = 'LOGIN_OUT'; 2 3 export const loginOut = () => { 4 return { 5 type: LOGIN_OUT 6 } 7 }