React-redux Spread operator in reducer returning error “unexpected token”

杀马特。学长 韩版系。学妹 提交于 2019-12-05 01:10:04

问题


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)



来源:https://stackoverflow.com/questions/38669951/react-redux-spread-operator-in-reducer-returning-error-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!