减速器中的 React-redux Spread 运算符返回错误“意外令牌" [英] React-redux Spread operator in reducer returning error "unexpected token"

查看:53
本文介绍了减速器中的 React-redux Spread 运算符返回错误“意外令牌"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我收到错误消息第 22 行出现意外令牌",指的是 ...todo不认为这与 Babel 预设有关,因为 ...state 工作得很好.当我在 map 函数中用 ...state 替换 ...todo 时,它返回相同的错误.

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

我的调用代码:

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
        }
    ])

推荐答案

实际上是关于预设.

数组展开是 ES2015 标准的一部分,您可以在这里使用它

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

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

然而,这里

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

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

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

你需要在 Babel 中启用对这个提议的支持:https://babeljs.io/docs/plugins/transform-object-rest-spread/ 或将其脱糖为 Object.assign 调用(参见 这部分提案)

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)

这篇关于减速器中的 React-redux Spread 运算符返回错误“意外令牌"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆