尝试在 React Native 中更新数组对象

时间:2021-08-01 14:21:12

标签: javascript reactjs react-native flatlist

为了简单起见,我制作了一个较短的版本。我知道这里的一些代码是错误的。我花了几个小时尝试不同的方法,但没有任何效果,所以我把它去掉了。

目标:我正在渲染一个 FlatList。我需要能够通过单击每个特定 FlatList 项目中的按钮来更新数组中每个相应对象中的“数量”。

因此,如果我在“abc”中单击“Increase QTY”,则“qty”数据将增加 1。

我在网上到处找,似乎无法靠近。任何帮助将不胜感激。

import React, { useState } from 'React';
import { View, Text, Button, FlatList } from 'react-native';

const DataApp = () => {
const [data, setData] = useState([
    { id: 1, name: 'abc', qty: 1 },
    { id: 2, name: 'def', qty: 2 },
    { id: 3, name: 'ghi', qty: 3 },
]);

const incQuantityHandler = (data) => {
    setData([...data, prevState => qty[prevState] + 1 ])
}

const Item = ({ item }) => (
    <View>
        <Text>{item.name}</Text>
        <Text>{item.qty}</Text>
        <Button title="Increase QTY" onPress={incQuantityHandler}/>
    </View>
)

const renderItem = ({ item }) => (
    <Item name={item.name} qty={item.qty} />
)

return (
    <View>
        <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        />
    </View>
)
}

export default DataApp;

1 个答案:

答案 0 :(得分:0)

根据您当前的设置,每当按下按钮时,都会使用事件对象调用 incQuantityHandler顺便说一下,您应该使用onClick

您可以使用箭头函数来传递您按下的按钮,否则使用包装函数:

onClick={() => incQuantityHandler(item.name)}
// or alternatively, but basically the same:
const wrapHandler = item => (() => incQuantityHandler(item.name));
onClick={wrapHandler(item)}

您的 incQuantityHandler 本身不正确。我建议重新阅读 React 文档并学习数组解构/扩展,但你可能想要这样的东西:

// Remember that now we get the item name instead
const incQuantityHandler = (itemName) => {
    // Use an arrow function to mutate data
    setData(data =>
        // Use map to map over all items
        data.map(item => {
            // Leave other items the way they are
            if (item.name !== itemName) return item;
            // Return a modified copy of our target item
            // where we changed the qty field
            return { ...item, qty: item.qty + 1 };
        }));
}