我們必須用{}
,而不是[]
而忘記使用Object.assign
一對夫婦的錯誤。
const reducer = (state = {}, action) => {
switch (action.type) {
case 'addConnection':
return Object.assign({}, state, {
connections: [
...state.connections,
{
[actions.compositeKey]: action.connection
}
]
});
default:
return state;
}
}
export default reducer;
也可能有助於看到它也以這種方式表達。它做同樣的事情,但我認爲它讀取更好一點
const reducer = (state = {}, {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return Object.assign({}, state, {
connections: state.connections.concat({
[compositeKey]: connection
})
});
default:
return state;
}
}
export default reducer;
或者,如果你使用Immutable,像這樣
import Immutable from 'immutable';
const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return state.set(
'connections',
state.get('connections').concat({
[compositeKey]: connection
})
);
default:
return state;
}
}
export default reducer;
當我使用第二個或第三個選項,它表示在編譯時出現「Uncaught ReferenceError:action is not defined」。 –
我忘了在'action'的解構中分配'type'。他們現在應該很好:) – naomik