简体   繁体   English

分配 object 不能通过 Rest/Spread 运算符工作

[英]Assigning object does not work through Rest/Spread Operator

I went to a trouble when doing hardcopy of an object.我在硬拷贝 object 时遇到了麻烦。

let error = { ...err }

So when I wrote that way I received a warning from ESLint "Rest/spread properties are not supported until node.js 8.3.0" and nothing was assigned to my error variable.因此,当我这样写时,我收到了来自 ESLint 的警告“在 node.js 8.3.0 之前不支持休息/扩展属性”,并且没有为我的错误变量分配任何内容。

I was sure that my node version is much higher than the required one, however I checked - it's ^14.1.0.我确信我的节点版本远高于所需的版本,但是我检查了 - 它是 ^14.1.0。

ESLint version - ^6.6.0. ESLint 版本 - ^6.6.0。

Lots of forums said to configure ESLint to make it work, so I added first:很多论坛都说要配置 ESLint 才能让它工作,所以我先补充一下:

"engines": {
    "node": ">=10.6.0"
}

And then:接着:

"env": {
    "es6": true
},
"parserOptions": {
    "ecmaVersion": 9,
    "sourceType": "module"
}

However, it still doesn't work.但是,它仍然不起作用。 err object is defined, when I try to implement in other ways it works, but when assigning through Spread - it doesn't.错误object 被定义,当我尝试以其他方式实现它时,它可以工作,但是当通过 Spread 分配时 - 它没有。

Does someone have any idea?有人有什么想法吗?

Thanks!谢谢!

PS when console.log(err.name) I get 'CastError' , when I console.log(error.name) after let error = {...err } , I get undefined. PS 当 console.log(err.name) 我得到'CastError' ,当我 console.log(error.name) 在let error = {...err }之后,我得到未定义。

PPS error inherits some properties from err, but property name is undefined. PPS 错误从 err 继承了一些属性,但属性名称未定义。

PPPS the snippet is PPPS 片段是

module.exports = (err, req, res, next) => {
    ...

    if(process.env.NODE_ENV === 'production') {
        let error = { ...err }
        if (error.name === 'CastError') {
            error = handleCastErrorDB(error)
        }
        sendErrorProd(error, res)
    }
}

However, this doesn't do what needed.但是,这并不能满足需要。 Thus, when I change if statement condition to err.name === 'CastError' instead of error.name === 'CastError' everything works.因此,当我将 if 语句条件更改为err.name === 'CastError'而不是error.name === 'CastError'一切正常。

Have the same problem on this Udemy course, the solution is:在这个 Udemy 课程上遇到同样的问题,解决方法是:

let error = Object.assign(err)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM