How to reset the state of a Redux store?

前端 未结 30 2491
陌清茗
陌清茗 2020-11-22 06:20

I am using Redux for state management.
How do I reset the store to its initial state?

For example, let’s say I have two user accounts (u1 and

30条回答
  •  借酒劲吻你
    2020-11-22 06:27

    in server, i have a variable is: global.isSsr = true and in each reducer, i have a const is : initialState To reset the data in the Store, I do the following with each Reducer: example with appReducer.js:

     const initialState = {
        auth: {},
        theme: {},
        sidebar: {},
        lsFanpage: {},
        lsChatApp: {},
        appSelected: {},
    };
    
    export default function (state = initialState, action) {
        if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
            state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
        }
        switch (action.type) {
            //...other code case here
            default: {
                return state;
            }
        }
    }
    

    finally on the server's router:

    router.get('*', (req, res) => {
            store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
            // code ....render ssr here
    });
    

提交回复
热议问题