我正在尝试了解Dan Abramov发布的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版本必须支持Spread运算符。
如果仍然不能,是否有任何方法可以添加一些独立的Polyfill以支持此语法?

这也是JSFiddle

最佳答案

The object spread syntax is not supported in most browsers at the minute。建议在ES7(又称ES2016)中进行添加。据我所知,没有办法对其进行填充,因为它使用了一种新的语法,而不仅仅是一个函数调用。

同时,您有两个选择。

1)使用Object.assign创建对象的更新版本,如下所示:

Object.assign({}, state, {
  completed: !state.completed
});

尽管在大多数浏览器a good example one is available on MDN中也需要对此进行填充,或者您可以使用第三方库的版本like the one in lodash

2)使用诸如Babel之类的转译工具,该工具可让您使用较新的语法编写代码,然后将其转换为可在所有浏览器中使用的版本。

关于javascript - Spread Operator无法用于基于Redux/ES6的示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35310830/

10-11 05:33