[英]How can I increase or decrease the quantity of a specific item?
我有一個理解問題。 我有不同的項目,每個用戶應該能夠選擇他想要多少。 文章存儲在 Firebase 中,帶有 Img、Name、Category。 用戶現在如何在不每次都將更新發送到數據庫的情況下增加項目? 只有當用戶點擊一個按鈕時,所有的數量,在每種情況下,都應該被寫入數據庫。 用戶也存儲在帶有密鑰和房間的數據庫中。
這是我的 Food Articel 代碼:
{filter?.map((art, idx) => {
return <Food key={idx} art={art}></Food>;
})}
....
export default function Food({ art }) {
const [artikel, setArtikel] = useState(art);
const [anzahl, setAnzahl] = useState(0);
const updateAnzahl = (action, artName) => {
if (action === "remove") {
setArtikel((prevState) => ({
...prevState,
[artName]: {
anzahl: anzahl - 1,
},
}));
} else {
setArtikel((prevState) => ({
...prevState,
[artName]: {
anzahl: anzahl + 1,
},
}));
}
};
<IconButton
aria-label="delete"
onClick={() => updateAnzahl("remove", art.name)}
>
<RemoveIcon fontSize="large"></RemoveIcon>
</IconButton>
<Typography variant="h5">{anzahl}</Typography>
<IconButton
aria-label="delete"
onClick={() => updateAnzahl("add", art.name)}
>
<AddIcon fontSize="large"></AddIcon>
</IconButton>
我會將用戶的當前訂單保留在瀏覽器的會話/本地存儲中,並在某個“提交”按鈕上更新數據庫。 小菜一碟:-)
順便提一句。 一個需要考慮的問題 - 如果用戶在您的應用程序上打開了多個選項卡/瀏覽器怎么辦 - 任何實例是否應該簡單地覆蓋其他數據或者您需要在它們之間進行一些同步?
這是帶有用於訂單管理的樣板代碼的鏈接: https://codesandbox.io/s/hotel-cafe-order-f5wp7d
import React, { useState } from 'react';
import {
SafeAreaView,
View,
Text,
FlatList,
StatusBar,
Button,
} from 'react-native';
const items = [
{
name: 'item 1',
qty: 0,
},
{
name: 'item 2',
qty: 0,
},
{
name: 'item 3',
qty: 0,
},
{
name: 'item 4',
qty: 0,
},
];
export default function App() {
const [data, setData] = useState(items);
const [refresh, setRefresh] = useState(''); // <- Add if your view not Rerender
const handleIncrease = (index) => {
const temp = data;
temp[index].qty = temp[index].qty + 1;
setData(temp);
setRefresh(Math.random()); // <- Add if your view not Rerender
};
const handleDecrease = (index) => {
const temp = data;
temp[index].qty = temp[index].qty - 1;
setData(temp);
setRefresh(Math.random()); // <- Add if your view not Rerender
};
const renderItem = ({ item, index }) => {
return (
<View
style={{
height: 50,
width: '90%',
marginLeft: '5%',
borderWidth: 1,
borderColor: 'black',
marginBottom: 10,
flexDirection: 'row',
}}>
<Text style={{ marginRight: 20 }}>{item.name}</Text>
<Button title="Increase" onPress={() => handleIncrease(index)} />
<Text style={{ marginHorizontal: 10 }}>{item.qty}</Text>
<Button title="Decrease" onPress={() => handleDecrease(index)} />
</View>
);
};
return (
<SafeAreaView style={{ flex: 1, marginTop: StatusBar.currentHeight }}>
<View style={{ flex: 1 }}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item, index) => String(index)}
/>
</View>
</SafeAreaView>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.