【发布时间】:2021-03-20 14:53:05
【问题描述】:
问题是,当我更新项目的数量时,父组件开始重新渲染修复重新渲染并仅在不重新渲染的情况下更新数组上的对象,如果有人可以帮助我吗? 提前致谢
父组件
export const ProductsScreen = ({ }) => {
const [Products, setProducts] = useState([
// sample of object props
{
id: '1',
name: 'first item',
volume: 500,
price: 150.25,
total: 4,
qty: 0
}]
const renderProducts = ({ item }) => {
const { qty } = item
return (
<ProductListItems
product={item}
qty={qty}
onAddItem={onAddItem}
onRemoveItem={onRemoveItem} />
)
}
const updateObjectInArray = (newProduct) => {
return setProducts(
Products.map((item) => {
if (item.id !== newProduct.id) {
return item
}
return {
...item,
...newProduct
}
})
)
}
const onAddItem = productId => {
let product = Products.find(i => {
return i.id === productId
})
const { total, qty } = product
const newProduct = {
...product,
qty: qty + 1,
total: total - 1
}
updateObjectInArray(newProduct)
}
const onRemoveItem = productId => {
let product = Products.find(i => {
return i.id === productId
})
const { total, qty } = product
const newProduct = {
...product,
qty: qty - 1,
total: total + 1
}
updateObjectInArray(newProduct)
}
return (
console.log("RERENDERD"),
<View style={styles.container} >
<SafeAreaView style={{ flex: 1, }}>
<FlatList
contentContainerStyle={{ paddingVertical: 15 }}
showsVerticalScrollIndicator={false}
data={Products}
renderItem={renderProducts}
keyExtractor={item => item.id}
/>
</SafeAreaView>
</View >
)
};
子组件
const ProductListItems = ({
product,
qty,
onAddItem,
onRemoveItem
}) => {
return (
// design here
)
};
export default memo(ProductListItems, (prevState, nextState) => prevState.qty === nextState.qty);
【问题讨论】:
-
我假设您使用
setProducts进行更改并且更改了产品,因此 ProductsScreen 将重新呈现,但它应该仅在项目是纯组件 (React.memo) 时重新呈现更改的项目 -
你建议在 setProducts 上做什么我不明白
标签: reactjs react-native react-redux react-native-flatlist