我正在尝试理解丹·阿布拉莫夫发布的Redux在线教程。目前,我正在进行以下示例:
Reducer composition with Arrays
下面是我在上面的示例之后的实践代码:
// 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");问题是,在todoReducer函数中,以下语法不起作用:
return {
...state,
completed: !state.completed
};我正在使用Firefox版本44.0,它在控制台中显示以下错误:
Invalid property id现在我猜我当前版本的Firefox必须支持扩展运算符。如果它无论如何都不支持,有没有办法添加一些独立的Polyfill来支持这种语法?
这也是JSFiddle
发布于 2016-02-10 17:27:14
The object spread syntax is not supported in most browsers at the minute。它被提议添加到ES7 (又名ES2016)中。据我所知,没有办法多填充它,因为它使用了一种新的语法,而不仅仅是一个函数调用。
同时,您有两个选择。
1)使用Object.assign创建object的更新版本,如下所示:
Object.assign({}, state, {
completed: !state.completed
});尽管这也需要在大多数浏览器中进行多填充- a good example one is available on MDN,或者您可以使用第三方库的版本like the one in lodash。
2)使用像Babel这样的转换工具,它允许您用更新的语法编写代码,然后将其转换为可在所有浏览器上运行的版本。
发布于 2018-02-17 04:57:26
如果任何使用Babel的人仍然有问题,这个功能可能无法与Babel开箱即用,您可能需要添加一个插件:http://babeljs.io/docs/plugins/transform-object-rest-spread/
然后用以下命令更新.babelrc
"plugins":"transform-object-rest-spread“
发布于 2016-02-10 17:27:22
您不能多填充语法。如果您希望在当前浏览器中执行,则需要使用像babel这样的工具来编译到旧版本的JavaScript。
https://stackoverflow.com/questions/35310830
复制相似问题