Sto cercando di capire le esercitazioni online di Redux pubblicate da Dan Abramov. Al momento sono sul seguente esempio:Operatore di diffusione che non funziona per l'esempio basato su Redux/ES6
Reducer composition with Arrays
Ecco il mio codice pratica seguendo l'esempio di cui sopra:
// Individual TODO Reducer
const todoReducer = (state, action) => {
switch(action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
};
case 'TOGGLE_TODO':
if (state.id != action.id) return state;
// This not working
/*
return {
...state,
completed: !state.completed
};
*/
//This works
var newState = {id: state.id, text: state.text, completed: !state.completed};
return newState;
default:
return state;
}
};
//TODOS Reducer
const todos = (state = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
todoReducer(null, action)
];
case 'TOGGLE_TODO':
return state.map(t => todoReducer(t, action));
default:
return state;
}
};
//Test 1
const testAddTodo =() => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
};
const stateAfter = [{
id: 0,
text: "Learn Redux",
completed: false
}];
//Freeze
deepFreeze(stateBefore);
deepFreeze(action);
// Test
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
//Test 2
const testToggleTodo =() => {
const stateBefore = [{id: 0,
text: "Learn Redux",
completed: false
}, {
id: 1,
text: "Go Shopping",
completed: false
}];
const action = {
type: 'TOGGLE_TODO',
id: 1
};
const stateAfter = [{
id: 0,
text: "Learn Redux",
completed: false
}, {
id: 1,
text: "Go Shopping",
completed: true
}];
//Freeze
deepFreeze(stateBefore);
deepFreeze(action);
// Expect
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
testAddTodo();
testToggleTodo();
console.log("All tests passed");
problema è, all'interno della funzione todoReducer, sintassi seguente non funziona:
return {
...state,
completed: !state.completed
};
sto usando Firefox versione 44.0 e mi mostra seguente errore in console:
Invalid property id
Ora suppongo che la mia versione corrente di Firefox debba supportare l'operatore di Spread. Se in ogni caso no, c'è un modo per aggiungere del Polyfill standalone per supportare questa sintassi?
Anche qui è la JSFiddle
Per completezza: [! '' ... non è un operatore] (https://stackoverflow.com/questions/37151966/what -is-spreadelement-in-ECMAScript documentazione-è-da-il-sam e-as-spread-oper/37152508 # 37152508) –