react native delete item form array by key



我试图通过特定的键从我的数组中删除一个项目。

这是我的代码:

生成多个TextInput的代码:

var OtherValuesArr = [];
const OtherValues = () =>{
for(let i=0; i<otherValuesNumber; i++){
var theOutPut = (
<View style={styles.otherValContainerLoop}>
<View style={styles.otherValContainerLoopCancel}>
<TouchablePlatform containerStyle={styles.otherValContainerLoopCancelTouch} onPress={()=>{otherValueRemove(i)}}>
<Icon name="minus" style={styles.otherValContainerLoopCancelTouchIcon} />
</TouchablePlatform>
</View>
<View style={styles.otherValContainerLoopInput}>
<TextInput
style={[styles.profileFormInputSection_INPUT,!variantValueHandler && {backgroundColor:'#fab8c0'}]}
onChangeText={(text) => {setOthersValue(text,i);}}
value={othervaluearr[i]}
placeholder={t(trans.optionvalue)}
placeholderTextColor={placeHolderTextColor}
keyboardType="default"
/>
</View>
</View>
);
OtherValuesArr[i]=theOutPut;
}
return OtherValuesArr;
}

处理输入(update,remove)的代码:

const [othervaluearr,setOtherValueArr] = useState([]);
const setOthersValue = (text,i) =>{
setOtherValueArr(oldArray => ({...oldArray,[i]:text}));
}
const otherValueRemove = (index) =>{
console.log(othervaluearr);
}

这是console.log(othervaluearr)的输出;:

{"0": "Asdasd", "1": "Asdasdxx"}

我想删除一个特定的键,例如:当index = 0时,我想删除"0"并获取具有以下值的新数组:

{"1": "Asdasdxx"}

请帮忙好吗?

试试这个:var index1 = othervaluearr.indexOf("Asdasd");

othervaluearr。拼接(index1 1);

问题是您在数组中保存了一个对象。你的数组有一个元素,它是带有你的值的对象。

要解决这个问题,你必须改变保存新数据的方式

1的解决方案

const setOthersValue = (text,i) =>{
setOtherValueArr(oldArray => [...oldArray,{key: i, value: text}];
}

,如果你想要一个稳定的键。如果你想要删除一个对象,你将用键x搜索这个对象,你将删除它。

,如果你不想要一个稳定的键。就做这个简单的解决方案。

2的解决方案

const setOthersValue = (text) =>{
setOtherValueArr(oldArray => [...oldArray, text];
}
const otherValueRemove = (index) =>{
othervaluearr.splice(index,1);
}

记住数组是包含[ ]的,对象是包含{ }

最新更新