gpt4 book ai didi

javascript - 需要折射的 ReactJs 函数(如果可能)

转载 作者:行者123 更新时间:2023-12-01 00:23:38 24 4
gpt4 key购买 nike

我为一个基本的电子商务商店编写了一些函数,但对我来说似乎都有点冗长。

也许有人对我如何折射它们有一些建议?

干杯。

1 - 根据操作将商品添加到购物车或愿望 list 的函数:

 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 })
}
}

最佳答案

对于第一个函数,您可以删除大部分声明:

  1. 一次性声明productToAdd
  2. 只需将值包含在数组中即可,而不是推送

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 })
}
}

对于第二个,如果没有更多上下文,就没有太多需要重构的内容:

  1. 使用内联 if 语句
  2. 使用速记属性分配
  3. 在 forEach 上使用过滤器

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 })
}
}

关于javascript - 需要折射的 ReactJs 函数(如果可能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59197606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com