2016-12-03 135 views
1

我似乎無法重置默認狀態;我怎麼做?我試過這個,但它所做的只是添加state來聲明並將其稱爲undefined。如何將狀態重置爲初始狀態?

const initialState = { 
    name: null, 
    coins: 0, 
    image: null, 
}; 

export default function reducer(state = initialState, action = {}) { 
    switch (action.type) { 
    case types.ADD_GROUP_COINS: 
     return { 
     ...state, 
     coins: state.coins + action.coins 
     }; 
    case types.DELETE_GROUP: 
     return { 
     state: undefined 
     }; 
    default: 
     return state; 
    } 
} 
+0

'case types.DELETE_GROUP: return initialState;'不工作,或者那不是你想要的? – Aurora0001

+0

那會給我'state:{state:{initialState}}'來代替。因爲它將它分配給'state'在'state'裏面' –

+0

我不認爲它會 - 'return {state:initialState}'會這樣做 - 'return initialState'應該按預期工作。 – Aurora0001

回答

2

的狀態恢復到initialState,只需return initialState,像這樣:

case types.DELETE_GROUP: 
    return initialState; 

請記住,在減速,您返回是新的狀態的對象。你不需要把它包起來的另一個對象,這樣的:

return { 
    state: ... 
} 

這會給你一個名爲您的狀態state屬性,這是不是你所需要的東西。

From the documentation

減速器是一個純粹的函數,它先前的狀態和動作,和返回下一狀態。

很容易混淆這個,所以要小心!如果您仍然不確定,請查看您的default案例:您將返回原來的state變量作爲新狀態,而不是{ state: state }您基本上使用當前DELETE_GROUP處理程序執行此操作。

+1

謝謝你的詳細答案!奇蹟般有效 –