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

IT技术 reactjs redux reducers
2021-05-12 00:51:17

我在https://github.com/tayiorbeii/egghead.io_redux_course_notes/blob/master/08-Reducer_Composition_with_Arrays.md 上关注了 Dan Abramov 的代码

我收到错误消息“第 22 行出现意外令牌”,指的是 ...todo 不认为这与 Babel 预设有关,因为 ...state 工作正常。当我在 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
        }
    ])
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/ 或将其 desugar 到Object.assign调用中(请参阅提议的这一部分