кто-нибудь знает, как сделать номер идентификатора сброса плоского списка после того, как я удалю из него 1 элемент
как и в моем названии, я борюсь с этим, хотя ниже приведен пример
{ id: '1', name: 'one' },
{ id: '2', name: 'two' },
{ id: '3', name: 'three' },
{ id: '4', name: 'four' },
это плоский список после удаления элемента с идентификатором '2'. Я хочу, чтобы идентификатор 3 стал 2, а идентификатор 4 стал 3, поэтому плоский список после удаления идентификатора 2 понравится
{ id: '1', name: 'one' },
{ id: '2', name: 'three' },
{ id: '3', name: 'four' },
вот мой код
export default function Listdata({ route }) {
const [itemData, newItem] = React.useState([]);
const [itemState, setItemState] = React.useState(itemData);
const [idmoi, incr,] = React.useState(1);
const [textNhapVao, setTextNhapVao] = React.useState('');
const tinhToanId = (t) => {
var idNew = [itemData.id];
incr(idNew - 1);
}
const themItem = () => {
var arrayMoi = [...itemData, { id: idmoi, name: textNhapVao }];
incr(idmoi + 1)
console.log('idddd')
console.log(idmoi)
setItemState(arrayMoi);
newItem(arrayMoi);
}
<View>
</View>
const keyboardVerticalOffset = Platform.OS === 'ios' ? 40 : 0
const xoaItem = (IItem) => {
console.log('routeeee')
console.log(route.params.paramKey)
setItemState(prevItemState => prevItemState.filter((_item, _Index) => _Index !== IItem));
}
return (
<Container style={styles.container}>
<View style={{
alignItems: 'center',
justifyContent: 'center',
borderBottomWidth: 1,
borderColor: '#d7d7d7',
}}>
<Text style={{ fontWeight: 'bold', fontSize: 30, color: 'green' }}>Xin Chào {route.params.paramKey}</Text>
</View>
<FlatList
data={itemState}
keyExtractor={(item, index) => index}
renderItem={({ item, index }) => (
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ marginLeft: 20 }}>
<Text style={{ fontSize: 30, color: 'red' }} >{item.id}{'\n'}{item.name}</Text>
</View>
<View style={{ justifyContent: 'center', marginRight: 20 }}>
<TouchableOpacity
style={{
width: '100%',
backgroundColor: 'red',
}}
activeOpacity={0.7}
onPress={() => xoaItem(index)}
>
<IconFE name='trash-2' size={30} style={{ color: 'orange' }} />
</TouchableOpacity>
</View>
</View>
)}
/>
<View
style={{
position: 'relative', height: 50,
borderTopWidth: 1,
borderColor: '#d7d7d7',
}}>
<KeyboardAvoidingView enabled behavior={Platform.OS === "ios" ? "padding" : null} keyboardVerticalOffset={keyboardVerticalOffset} >
<View
style={{
alignItems: 'center', position: 'relative',
flexDirection: 'row',
justifyContent: 'space-between',
marginLeft: 20,
marginRight: 20,
}}>
<Input
onChangeText={data => setTextNhapVao(data)}
placeholder='Nhập Vào Đây'></Input>
<TouchableOpacity
title="Thêm"
onPress={themItem}>
<IconFE name='check-square' size={30} style={{ color: 'blue' }} />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</View>
</Container>
)
}
и ниже мой плоский список скриншотов: https://uphinh.org/image/9OLoCN
4 ответа
Вы можете взять функцию, которая удаляет объект по заданному индексу.
Функция берет удаленный массив, берет объект в начале и получает цикл от индекса до конца и обновляет все
Насколько я понимаю, ваш не продолжается (
1,2,3...
), потому что в этом случае вам вообще не нужно мутировать, вы можете просто использовать
array
индексы вместо этого. Во всяком случае, если вы предполагаете, что
id
не продолжается, мы можем попробовать следующий алгоритм:
- Найдите удалить индекс,
- Элемент карты
n
кn+1
для индексов выше, чем индекс удаления, - Удалите последний элемент (это будет наш последний элемент удаления, который был сдвинут до конца).
Пример кода:
Из предоставленного массива удалите выбранный массив методом splice, найдя его индекс
Рабочий пример: https://snack.expo.io/@msbot01/137768
import React, { Component } from 'react';
import {View, Text, StyleSheet, Image, TouchableOpacity, Dimensions, FlatList} from 'react-native';
export default class SupervisorDashboard extends Component<Props> {
constructor(props) {
super(props);
this.state = {
userData:[
{id:1, name:"One"},
{id:2, name:"Two"},
{id:3, name:"Three"},
{id:4, name:"Four"},
{id:5, name:"Five"},
{id:6, name:"Six"},
]
}
}
componentDidMount(){
}
removeItem(index){
this.state.userData.splice(index, 1);
var array = []
// console.log(JSON.stringify(this.state.userData))
for(var i=0; i< this.state.userData.length; i++){
var eachElement = {id: (i+1), name: this.state.userData[i].name }
array.push(eachElement)
}
console.log(JSON.stringify(array))
this.setState({})
}
renderItem(item, index){
// console.log(item.id)
return(
<View style={{height:60, width:'90%', marginTop:10, marginLeft:'5%', marginRight:'5%', flexDirection:'row', justifyContent:'space-between', alignItems:'center', borderRadius:10, borderWidth:1, borderColor:'#ececec', padding:10}}>
<Text>{item.id}</Text>
<Text>{item.name}</Text>
<TouchableOpacity onPress={()=>{this.removeItem(index)}} style={{marginRight:10, backgroundColor:'grey', height:'100%', justifyContent:"center", borderRadius:10, padding:10}}>
<Text>Click to remove</Text>
</TouchableOpacity>
</View>
)
}
render(){
return(
<View style={{flex:1, backgroundColor:'white'}}>
<FlatList
data={this.state.userData}
renderItem={({ item, index })=>this.renderItem(item, index)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
const styles = StyleSheet.create({
background: {
backgroundColor: 'red'
}
});
Вы легко добьетесь такого результата
- Найдите индекс элемента, который вы хотите удалить, используя findIndex
- Затем разделите массив на две половины
- Добавьте один во второй массив после того, как он будет проанализирован в
int
. - присоединиться к массиву.
- Обязательно закрывайте угловой корпус, если элемент не в
arr
.