首页 > 解决方案 > React Native 更新一个平面列表项

问题描述

我想在单击时更新特定的 Flatlist 行,我该怎么做?我找到的解决方案都是 using extraData={this.state},这在我的代码中不起作用。

const [records,setRecords] = useState([]);
//add initial data to records
...
return (
<FlatList
    data={records}
    keyExtractor={item => item.id}
    renderItem={itemData =>
        <RecordItem
            onSelect={() => {
                props.navigation.navigate({...})
                }
            } 
            onApply={()=>{
                // in my RecordItem these is a button to call onApply(), 
                and I want to update the Flatlist when I click this button

                var res = applyHandler();
                return res;
            }}
        >
        </RecordItem>
     }
/>)

标签: react-native

解决方案


要更新您的平面列表项,您只需更新它正在呈现的数据,为此,在您的onApply函数中您知道可以更新记录索引的项索引,例如:

const [records,setRecords] = useState([]);
//add initial data to records
...
return (
<FlatList
    data={records}
    keyExtractor={item => item.id}
    renderItem={itemData =>
        <RecordItem
            onSelect={() => {
                props.navigation.navigate({...})
                }
            } 
            onApply={()=>{
                // here you will get reference to record item index, 
                const itemIndex = itemData.index;
                const modRecords = [...records];
                modRecords[itemIndex].title = 'NEW TITLE';
                // assuming title is what you want to change
                // now just update the records using setRecords
                setRecords(modRecords);
            }}
        >
        </RecordItem>
     }
/>)

推荐阅读