React-redux Spread operator in reducer returning e

2019-03-30 07:41发布

问题:

I followed Dan Abramov's code at https://github.com/tayiorbeii/egghead.io_redux_course_notes/blob/master/08-Reducer_Composition_with_Arrays.md

I am getting error message "Unexpected token at line 22" referring to the ...todo Didn't think it's to do with Babel presets as ...state is working just fine. When I substitute ...todo with ...state inside the map function, it returns the same error.

///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;
      }
     }

My calling code:

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:

It is about presets, actually.

Array spread is part of ES2015 standard and you use it here

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

However, here

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

you use object spread which is not part of the standard, but a stage 2 proposal.

You need to enable support of this proposal in Babel: https://babeljs.io/docs/plugins/transform-object-rest-spread/ or desugar it into Object.assign calls (see this part of the proposal)