【发布时间】:2021-12-31 18:47:32
【问题描述】:
#React Native 我正在尝试将数据从数组获取到选取器。数组将数据发送到选择器没有任何问题,但是当我在下拉列表中选择一个项目时 " 无法反应未定义的属性 'forEach' 弹出此错误
const ListItem = ({ item, onSubtract, onAdd }) => (
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
<Text style={styles.cardText} >{item.name} - </Text>
<Text style={styles.cardText} >{item.price}</Text>
</View>
<View style={{ flexDirection: 'row', flex: 1, alignItems: 'center' }}>
<Button title="Subtract" onPress={onSubtract} />
<Text style={styles.cardText} >{item.quantity}</Text>
<Button title="Add" onPress={onAdd} />
</View>
</View>
);
const ExistingCustomerScreen = () => {
const [products, setProducts] = React.useState([
{ _id: 1, name: 'Item 1', price: 50, quantity: 0 },
{ _id: 2, name: 'Item 2', price: 29, quantity: 0 },
{ _id: 3, name: 'Item 3', price: 200, quantity: 0 },
]);
const [products2, setProducts2] = React.useState()
const onSubtract = (item, index) => {
const nextProducts = [...products];
nextProducts[index].quantity -= 1;
setProducts(nextProducts);
};
const onAdd = (item, index) => {
const nextProducts = [...products];
nextProducts[index].quantity += 1;
setProducts(nextProducts);
};
let totalQuantity = 0;
let totalPrice = 0;
products.forEach((item) => {
totalQuantity += item.quantity;
totalPrice += item.quantity * item.price;
});
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Picker
style={{ color: '#000' }}
selectedValue={products}
onValueChange={setProducts}
>
{products !== "" ? (
products.map(item => {
return <Picker.Item label={item.name} value={item.id} />;
})
) : (
<Picker.Item label="Loading..." value="0" />
)}
</Picker>
</View>
<FlatList
data={products}
renderItem={({ item, index }) => (
<ListItem
item={item}
onSubtract={() => onSubtract(item, index)}
onAdd={() => onAdd(item, index)}
/>
)}
keyExtractor={(item) => item._id}
/>
</SafeAreaView>
)
}
#React Native 我正在尝试将数据从数组获取到选取器。数组将数据发送到选择器没有任何问题,但是当我在下拉列表中选择一个项目时 " 无法反应未定义的属性 'forEach' 弹出此错误
【问题讨论】:
标签: reactjs react-native foreach react-hooks