小编典典

减速器中的React-redux Spread运算符返回错误“意外令牌”

reactjs

我在https://github.com/tayiorbeii/egghead.io_redux_course_notes/blob/master/08-Reducer_Composition_with_Arrays.md中遵循了Dan
Abramov的代码

我收到错误消息“第22行出现意外的令牌”,这是指… todo认为与Babel预设无关,因为…状态工作正常。当我在map函数中用…
state替换… 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
        }
    ])

阅读 267

收藏
2020-07-22

共1个答案

小编典典

实际上,它与预设有关。

数组扩展是ES2015标准的一部分,您可以在此处使用

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

但是这里

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

您使用的对象传播不是标准的一部分,而是阶段2的提议

您需要在Babel中启用此建议的支持:https : //babeljs.io/docs/plugins/transform-object-rest-
spread/或将其解压缩为Object.assign调用(请参阅建议的这一部分

2020-07-22