注销时清除反应组件状态

时间:2020-01-14 15:32:33

标签: javascript reactjs redux react-component

我有一个单页应用程序,其中有一个加载用户数据的react组件。注销后,该数据将保留。除了清除Redux状态外,如何清除此组件的状态?在redux reducer中是否也清除了单个组件状态?

现在我像这样处理状态的redux清除:

// reducers / auth.js

export default function authReducer(state = initialState, action) {
    switch (action.type) {
        ... 
        case AUTH_LOGOUT_USER:
            return Object.assign({}, state, {
                // this resets redux state, but not react state?
                isAuthenticated: false,
                isAdmin: false,
                token: null,
                userName: null,
                organization: null,
                logo: null,
                statusText: 'You have been successfully logged out.'
            });
        ...
        default:
            return state;
    }
}

// actions / auth.js

export function authLogout() {
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('user');
    return {
        type: AUTH_LOGOUT_USER
    };
}

// component.jsx

...
userData=fetchUserData()
this.setState(userData)
...

2 个答案:

答案 0 :(得分:0)

只需在Component函数中将logout状态设置回其初始值即可:

const logout = () => {
    this.props.authLogout() // your redux action
    this.setState({}) // set this to whatever your initial state is
}

答案 1 :(得分:0)

您只需要重置redux的存储。卸下组件后,组件的内部状态将自动清除。