我配置了 eslint,以便它根据需要使用 arrow-body-style:
arrow-body-style: ["error", "as-needed"]
但由于某种原因,我在下面收到错误。
router.get('/', (req, res, next) => {
Product.find({})
.select('name price _id')
.then(items => {
const response = {
count: items.length,
products: items.map(item => { // eslint points the error here
return {
name: item.name,
price: item.price,
_id: item._id,
request: {
type: 'GET',
url: `http://localhost:3000/products/${item._id}`
}
};
})
};
res.status(200).json(response);
})
.catch(error => {
console.log(error);
res.status(500).json({ message: 'Server error' });
});
});
Run Code Online (Sandbox Code Playgroud)
我究竟应该如何重写我的代码?
使用arrow-body-style: ["error", "as-needed"]配置是多余的,因为它是默认行为。您不需要再次设置它,因为它已经设置为默认表单。
如所须
使用默认“按需”选项的此规则的错误代码示例:
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
let foo = () => {
return 0;
};
let foo = () => {
return {
bar: {
foo: 1,
bar: 2,
}
};
};
Run Code Online (Sandbox Code Playgroud)
使用默认“按需”选项的此规则的正确代码示例:
/*eslint arrow-body-style: ["error", "as-needed"]*/
/*eslint-env es6*/
let foo = () => 0;
let foo = (retv, name) => {
retv[name] = true;
return retv;
};
let foo = () => ({
bar: {
foo: 1,
bar: 2,
}
});
let foo = () => { bar(); };
let foo = () => {};
let foo = () => { /* do nothing */ };
let foo = () => {
// do nothing.
};
let foo = () => ({ bar: 0 });
Run Code Online (Sandbox Code Playgroud)
在您的代码示例中应该是这样的:
router.get('/', (req, res, next) => {
Product.find({})
.select('name price _id')
.then(items => {
const response = {
count: items.length,
products: items.map(item => ({ // no more errors
name: item.name,
price: item.price,
_id: item._id,
request: {
type: 'GET',
url: `http://localhost:3000/products/${item._id}`
});
})
};
res.status(200).json(response);
})
.catch(error => {
console.log(error);
res.status(500).json({ message: 'Server error' });
});
});
Run Code Online (Sandbox Code Playgroud)
由于您只是返回一个普通对象,因此不需要额外的一对大括号 和return。将对象括在括号中({ ... }),就像隐式返回一样。
尝试省略return关键字并将结果括在括号中:
products: items.map(item => ({
name: item.name,
price: item.price,
_id: item._id,
request: {
type: 'GET',
url: `http://localhost:3000/products/${item._id}`
}
}))
Run Code Online (Sandbox Code Playgroud)