• 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 }
  • 相关阅读:
    [Leetcode 56] 55 Jump Game
    [Leetcode 57] 61 Rotate List
    [Leetcode 61] 73 Set Matrix Zeros
    [Leetcode 62] 74 Search a 2D Matrix
    [Leetcode 64] 78 Subsets
    [Leetcode 63] 77 Combinations
    [Leetcode 58] 63 Unique Path II
    python学习笔记第1章节 基础知识
    python学习笔记第2章节 分支,循环,还有条件
    visual studio 2008 试用版评估期已结束的解决方法(转载)
  • 原文地址:https://www.cnblogs.com/rion1234567/p/9559233.html
Copyright © 2020-2023  润新知