【发布时间】:2021-09-01 21:53:17
【问题描述】:
下面是我的代码:
const ProductData = () => {
const [data, setData] = useState([])
const x = [{"product": {"product_description": "XYZ", "product_name": "Product1"}, "quantity": 1}]
setData(x);
function onChangeQuantity(i, type){
let quant = data[i].quantity;
if (type) {
quant += 1;
data[i].quantity = quant;
setData(data);
console.log(data);
} else if (type === false && quant >= 2) {
quant -= 1;
data[i].quantity = quant;
setData(data);
console.log(data);
} else if (type === false && quant === 1) {
data.splice(i, 1);
setData(data);
}
}
return(
<View>
{data.map((item, index) => (
<View key={index}>
<Text>
{item.product.product_name}
</Text>
</View>
<View style={styles.container4}>
<TouchableOpacity
onPress={() => onChangeQuantity(index, false)}>
<Text> Decrement Value </Text>
</TouchableOpacity>
<Text>{item.quantity}</Text>
<TouchableOpacity
onPress={() => onChangeQuantity(index, true)}>
<Text> Increment Value </Text>
</TouchableOpacity>
</View>
</View>
))}
</View>
)
}
现在面临的问题是 - 每当我点击增量值/减量值时,数量都会更新,但更新后的值不会显示在 return 语句中。按下增量值按钮后的示例控制台日志如下:
[{"product": {"product_description": "Product2", "product_name": "Product2"}, "quantity": 2}]
但更改并未反映在视图中。如何在单击按钮后立即显示更新的数量。请让我知道我哪里错了。提前非常感谢。
【问题讨论】:
标签: reactjs react-native react-hooks use-effect use-state