javascript - React-native 中的 AsyncStorage 存在问题
问题描述
我正在尝试在我的代码中使用一些小购物车系统,但我的购物车中只有一个值。
出于某种原因,它似乎将成为一个数组的开放数组
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 DocsremoveItem()
中的方法以删除项目。
推荐阅读
- redis - Nestjs 和 GraphQL 的日期对象反序列化问题(使用微服务)
- arrays - 嘿,我最近学习了递归,我想知道为什么我的代码不能在 c 中工作
- windows-10 - 我正在尝试将 W7 Delphi10.4 升级到新的 W10 Pc 10.4.2 - 有问题
- r - R - 文件中的错误(con,“r”):无法打开与
- reactjs - 我正在尝试制作 CRUD,但无法发送
- pandas - 条形图对所有列使用 for 循环,而与数据类型无关
- sql - 加入与填充 | 抬头
- javascript - 获取 Json 值并使用 Javascript 创建数组
- c++ - 删除复杂类型的数组
- java - 在 Azure 中部署时 OAuth2 循环和不正确重定向