2017-10-16 120 views
0

我正在嘗試基於Dan Abramov here的建議來實現redux重置狀態操作。我設置我的減速器和存儲,像這樣:Redux - 重置狀態

Index.js:

import {applyMiddleware,createStore} from 'redux'; 
import combineReducers from './reducers/index'; 
import {wrapStore,alias} from 'react-chrome-redux'; 
import thunk from 'redux-thunk'; 
import aliases from './aliases/aliases'; 

const combineAppReducers = (state, action) => { 
    if (action.type === 'LOG_OUT') { 
    state = undefined; 
    } 

    return combineReducers(state, action) 
} 

const middlewares = [alias(aliases), thunk]; 

const store = createStore(combineAppReducers,applyMiddleware(...middlewares)); 

wrapStore(store, { 
    portName: 'example' 
}); 

Reducers.js:

import {combineReducers} from 'redux'; 
import userAuthReducer from './userAuthReducer'; 
import manageTeamsReducer from './manageTeamsReducer'; 

function lastAction(state = null, action) { 
    return action; 
} 

export default combineReducers({ 
    userAuthReducer,manageTeamsReducer,lastAction 
}); 

看起來好像我已經正確設置好一切,但應用程序沒有重置狀態,任何人都可以發現我出錯的地方嗎?

這裏是它的另一篇文章,我更緊隨其後:

https://medium.com/@agungsantoso/how-to-reset-the-state-of-a-redux-store-7f9d85b190bc

+0

你試過設置狀態到一個空對象?像'state = {}'? – lumio

+0

你還得到什麼錯誤? – lumio

+0

我認爲這不是最好的方法,但是,您可以將您的狀態恢復爲第一個調度值:'@@ INIT'操作。 – Hitmands

回答

0

它做工精細。 你可以查看我的代碼片段。 你能上傳錯誤日誌嗎?

function lastAction(state = null, action) { 
 
    return action; 
 
} 
 

 
function counter(state = 0, action) { 
 
    if (action.type === 'INC') { 
 
     return state+1; 
 
    } 
 
    
 
    return state; 
 
} 
 

 
const combineAppReducers = Redux.combineReducers({ 
 
    lastAction, 
 
    counter 
 
}); 
 

 
const combineReducers = (state, action) => { 
 
    if (action.type === 'LOG_OUT') { 
 
    state = undefined; 
 
    } 
 
    return combineAppReducers(state, action) 
 
} 
 

 
const store = Redux.createStore(combineReducers); 
 

 
const root = document.createElement('ul'); 
 
document.body.append(root); 
 
let unsubscribe = store.subscribe(() =>{ 
 
    const li = document.createElement('li'); 
 
    li.append(store.getState().counter); 
 
    root.append(li); 
 
}) 
 

 
store.dispatch({type: 'INC'}); 
 
store.dispatch({type: 'INC'}); 
 
store.dispatch({type: 'INC'}); 
 
store.dispatch({type: 'LOG_OUT'}); 
 
store.dispatch({type: 'INC'});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.js"></script> 
 
</head> 
 
<body> 
 
</body> 
 
</html>

+0

我得到了編譯代碼(已編輯上述)。我的行動都是如何應對新的整合,但註銷行動仍然不會重置狀態...... –