我已经为一家基本的电子商务商店编写了一些功能,但对我来说似乎都有些冗长。
也许有人对我如何折射他们提出了一些建议?
干杯。
1-一项基于动作将商品添加到购物车或愿望清单的功能:
addToFunnelHandler = (uuid, price, title, action) => {
let productToAdd = {}
productToAdd.uuid = uuid
productToAdd.price = price
productToAdd.title = title
if (action === 'bag') {
let productsInBag = [...this.state.productsInBag]
productsInBag.push(productToAdd)
this.setState({ productsInBag: productsInBag, bagCount: this.state.bagCount + 1, bagTotal: this.state.bagTotal + price })
} else if (action === 'wishlist') {
let productsInWishlist = [...this.state.productsInWishlist]
productsInWishlist.push(productToAdd)
this.setState({ productsInWishlist: productsInWishlist, wishlistCount: this.state.wishlistCount + 1})
}
}
2-相同但相反,从渠道中删除一项:
removeFromFunnelHandler = (uuid, price, action) => {
if (action === 'bag') {
let productsInBag = [...this.state.productsInBag]
productsInBag.forEach((product, index) => {
if (product.uuid === uuid) { productsInBag.splice(index, 1) }
})
this.setState({ productsInBag: productsInBag, bagCount: this.state.bagCount - 1, bagTotal: this.state.bagTotal - price })
} else if (action === 'wishlist') {
let productsInWishlist = [...this.state.productsInWishlist]
productsInWishlist.forEach( (product, index) => {
if (product.uuid === uuid) { productsInWishlist.splice(index, 1) }
})
this.setState({ productsInWishlist: productsInWishlist, wishlistCount: this.state.wishlistCount - 1 })
}
}
最佳答案
至于第一个函数,您可以删除大多数声明:
一口气宣布productToAdd
而不是推送,只需将值包含在数组中
addToFunnelHandler = (uuid, price, title, action) => {
let productToAdd = { uuid, price, title }
if (action === 'bag') {
this.setState({ productsInBag: [...this.state.productsInBag, productToAdd], bagCount: this.state.bagCount + 1, bagTotal: this.state.bagTotal + price })
} else if (action === 'wishlist') {
this.setState({ productsInWishlist: [...this.state.productsInWishlist, productToAdd], wishlistCount: this.state.wishlistCount + 1 })
}
}
第二,没有更多上下文,没有太多可重构的内容:
使用内联if语句
使用简写属性辅助
对每个使用过滤器
removeFromFunnelHandler = (uuid, price, action) => {
if (action === 'bag') {
const productsInBag = [...this.state.productsInBag].filter(product => product.uuid !== uuid)
this.setState({ productsInBag, bagCount: this.state.bagCount - 1, bagTotal: this.state.bagTotal - price })
} else if (action === 'wishlist') {
const productsInWishlist = [...this.state.productsInWishlist].filter(product => product.uuid !== uuid)
this.setState({ productsInWishlist, wishlistCount: this.state.wishlistCount - 1 })
}
}