从地图返回的React对象传播(ES6) [英] React object spread (ES6) returned from map

查看:84
本文介绍了从地图返回的React对象传播(ES6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这为什么起作用:

return elements.map((e)=> {return Object.assign({}, e, {selected:true})});

但这不是:

return elements.map((e)=> {...e, {selected: true}});

?

ES6/Babel/React的新手,请留意.

New to ES6 / Babel / React, have mercy.

更新: 移至此后(按照建议):

UPDATE: After moving to this (as suggested):

return elements.map(e => ({...e, selected: true }));

出现此错误:

尽管传播正在项目的其他地方起作用:

Though the spread is working elsewhere in the project:

        return [
            ...state,
            element(undefined, action)
        ]

推荐答案

箭头函数中对象的隐式返回应该包装在括号中,以便解释器知道它不是一个块.

An implicit return of an object from an arrow function should be wrapped in parens so the interpreter knows it's not a block.

所以return elements.map(e => ({...e, selected: true }));

还修复了所选属性的语法,如azium所指出的那样,不应将其包装在方括号中.

Also fixed the syntax for the selected property, it shouldn't be wrapped in brackets as azium pointed out.

请参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

您意外的令牌错误可能是由于babel不支持建议的对象传播.数组扩展为es6.按照下面的答案使用插件可以解决此问题.我首选的包含对象传播的方法是babel阶段0,因为您还可以获得其他很酷的功能,例如::绑定运算符.对象传播是阶段2,因此如果不想包含阶段1和0,也可以使用它.

Your unexpected token error is probably due to babel not supporting the proposed object spread. Array spread is es6. Using the plugin as in the answer below will solve this issue. My preferred way to include object spread is babel stage 0, as you also get other cool features like the :: binding operator. Object spread is stage 2, so you could also use that if you don't want to include stages 1 and 0.

https://babeljs.io/docs/plugins/preset-stage-0/

这篇关于从地图返回的React对象传播(ES6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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