React-redux Spread运算符在reducer中返回错误“意外令牌”

时间:2016-07-30 02:58:03

标签: reactjs redux reducers

我在https://github.com/tayiorbeii/egghead.io_redux_course_notes/blob/master/08-Reducer_Composition_with_Arrays.md

跟随Dan Abramov的代码

我收到错误消息“第22行的意外令牌”,指的是...待办事项 不认为这与Babel预设有关......状态正常。当我在map函数中用...替换... todo时,它会返回相同的错误。

///Reducer//
    export default (state=[], action) => {
      switch (action.type) {

        case 'ADD_TODO':
            return [...state,
                {
                 id:action.id,
                 text: action.text,
                 completed:false
                }
            ];

         case 'TOGGLE_TODO':
          return state.map(todo => {
            if (todo.id !== action.id) {
              return todo;
            }

            return {
              ...todo, //returning error
              completed: !todo.completed
            };
          });


        default:
            return state;
      }
     }

我的主叫代码:

it('handles TOGGLE_TODO', () => {
    const initialState = [
        {
        id:0,
         text: 'Learn Redux',
         completed: false
        },
        {
        id:1,
         text: 'Go Shopping',
         completed: false
        }
    ];


    const action = {
        type: 'TOGGLE_TODO',
        id: 1
    }




    const nextstate = reducer(initialState,action)



    expect (nextstate).to.eql([
        {
        id:0,
         text: 'Learn Redux',
         completed: false
        },
        {
        id:1,
         text: 'Go Shopping',
         completed: true
        }
    ])

1 个答案:

答案 0 :(得分:6)

实际上是预设。

Array spread是ES2015标准的一部分,你可以在这里使用

        return [...state,
            {
             id:action.id,
             text: action.text,
             completed:false
            }
        ];

然而,这里

        return {
          ...todo, //returning error
          completed: !todo.completed
        };

您使用的object spread不是标准的一部分,而是a stage 2 proposal

您需要在Babel中启用对此提案的支持:https://babeljs.io/docs/plugins/transform-object-rest-spread/或将其解析为Object.assign次来电(请参阅this part of the proposal