[英]Set State Problem For Reusable Component React Native
I try to make a reusable card where I can increment quantities for different items.我尝试制作一张可重复使用的卡片,我可以在其中增加不同物品的数量。 I tried in many ways but I couldn't make it work.
我尝试了很多方法,但我无法让它发挥作用。 I use a flatlist to show every card.
我使用平面列表来显示每张卡片。 This is the card:
这是卡片:
export default function Card(props) {
return (
<View style={styles.card}>
<Text>{props.children}</Text>
<TouchableOpacity
onPress={() => {
console.log(props.number);
props.set(props.number+1)
}}
>
<FontAwesome size={30} name="plus" color="red" />
</TouchableOpacity>
</View>
);
}
This is where I use the flatlist:这是我使用平面列表的地方:
export default function User() {
const [objects, setObjects] = useState([
{
id: "1",
name: "pants",
quantity: 0,
},
{
id: "2",
name: "t-shirt",
quantity: 0,
},
]);
return (
<SafeAreaView>
<FlatList
data={objects}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<Card number={item.quantity} set = {setObjects}>
{item.name}
</Card>
)}
/>
</SafeAreaView>
);
}
Will this work?这行得通吗? Call
props.set
like this:像这样调用
props.set
:
props.set({
...props.item,
quanitity: props.item.quantity + 1,
})
And Card
:和
Card
:
<Card
item={item}
set={item => setObjects(objs => {
for (const obj of objs) {
if (obj.id === item.id) {
obj.quantity++
break
}
}
return objs
}}
>
If that works, I'd still suggest some refactoring:如果可行,我仍然建议进行一些重构:
<Card
item={item}
add={() => setObjects(objs => {
for (const obj of objs) {
if (obj.id === item.id) {
obj.quantity++
break
}
}
return objs
}}
>
and和
<TouchableOpacity onPress={props.add}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.