我正在尝试在我的代码中使用一些小购物车系统,但我的购物车中只有一个值。
出于某种原因,它似乎将一个开放数组变成一个数组
addCart=()=>{
var sepet=AsyncStorage.getItem("sepet").then(req=>JSON.parse(req)).then(json=>{
var sepet=[json];
sepet.push({isim:this.props.title,fiyat:this.props.fiyat,image:this.props.image});
AsyncStorage.setItem("sepet",JSON.stringify(sepet));
console.log(sepet)
});
}
然后我正在尝试
export default class aksiyos extends React.Component {
constructor(props) {
super(props);
this.state = {
ApiTitle: [],
}
}
componentDidMount() {
var sepet=AsyncStorage.getItem("sepet").then(req=>JSON.parse(req)).then(json=>{
this.setState({ApiTitle: json });
});
}
render() {
return (
<View style={{backgroundColor: "white"}}>
<ScrollView>{this.state.ApiTitle.map((ids, i)=>
<Text>{ids.isim}</Text>
)}
</ScrollView>
</View>
);
}
}
但它只显示我选择的最后一个对象
我也不知道如何删除这些对象。
您将您的项目保存为一个数组,但您也将获得这些并将它们放入一个新数组中。您只渲染最后一个项目是有道理的,因为这可能是唯一不在另一个数组中的项目。您只需使用扩展运算符即可解决此问题。
const sepets = await AsyncStorage.getItem("sepet")
.then(req=>JSON.parse(req))
.then(json => {
const sepet=[...json]; // <-- If we saved an array, makes sense to spread it in a new array. Otherwise we get [[sepet], sepet]"
sepet.push({
isim:this.props.title,
fiyat:this.props.fiyat,
image:this.props.image
});
AsyncStorage.setItem("sepet",JSON.stringify(sepet)); // <-- save the array
console.log(sepet)
return sepet;
});
查看React Native Docs 中的removeItem()
方法以删除项目。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句