Javascript eslint箭头主体样式问题
我配置了eslint,以便它根据需要使用箭头主体样式:Javascript eslint箭头主体样式问题,javascript,eslint,Javascript,Eslint,我配置了eslint,以便它根据需要使用箭头主体样式: 箭头体样式:[“错误”,“根据需要”] 但由于某种原因,我在下面得到了一个错误 router.get('/', (req, res, next) => { Product.find({}) .select('name price _id') .then(items => { const response = { count: items.length, produc
箭头体样式:[“错误”,“根据需要”]
但由于某种原因,我在下面得到了一个错误
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' });
});
});
我应该如何重新编写代码?尝试省略
return
关键字并将结果括在括号中:
products: items.map(item => ({
name: item.name,
price: item.price,
_id: item._id,
request: {
type: 'GET',
url: `http://localhost:3000/products/${item._id}`
}
}))
使用
箭头体样式:[“错误”,“根据需要”]
配置是多余的,因为这是默认行为。您不需要再次设置它,因为它已经设置为默认表单
根据需要
使用默认“按需”选项的此规则的错误代码示例:
使用默认“按需”选项的此规则的正确代码示例:
在您的代码示例中,应该是这样的:
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' });
});
});
由于您只是返回一个普通对象,因此不需要额外的一对大括号和return
。将对象包装在括号({…})
中,就像隐式返回的对象一样
/*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 });
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' });
});
});