[英]how to increase or decrease the count based on array index
我需要根据数组索引增加或减少产品数量。 使用此 function 数据值时正在更新,但 flatlist 无法呈现更新后的值
import React ,{useState} from 'react';
import { Text, View, StyleSheet,FlatList,Button } from 'react-native';
const addCount = () => {
const [data,setData] = useState([{
id : 1,
name : "Mongo",
price : 30,
qty : 1
},
{
id : 2,
name : "lemon",
price : 30,
qty : 1
}])
const addQty = (ind) => {
setData(data[ind].qty + 1)
}
return (
<View>
<FlatList
data={data}
renderItem= {({item,index})=>{
return (
<View>
<Text>name: {item.name}</Text>
<Text>qty : {item.qty}</Text>
<Text>price : {item.price}</Text>
<Button title = "add Qty" onPress = {()=>{
addQty(index)
}}/>
</View>
)
}}
keyExtractor={item => item.id}
/>
</View>
)
}
export default addCount
谢谢!!
您不应该直接改变数组,而是必须提供一个新数组才能更新state所以尝试:
setData(data.map((obj,index)=> index == ind ? { ...obj, qty:obj.qty+1} : obj ))
只需如下更新代码,并使其变得如此简单,因为我们正在迭代 json object,我们不想使用扩展运算符,
setData(data.map((obj, index) => index == ind? obj.qty++: obj))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.