react中手动重置redux
前段时间使用redux在react-native中,安卓后退两次关闭后redux未清空的问题,一直觉得处理的不够优雅,没有根本解决问题。
后来发现再退出登录后,也有部分数据因为redux的逻辑处理数据缓存问题被留了下来,造成一些意料之外的问题,于是要彻底解决重置redux的办法。
我的解决方法是,写一个action用来处理退出登录,每个reducer都监听这个type,return初始值。
//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 }