简体   繁体   English

React-native中的AsyncStorage存在问题

[英]There is a problem about AsyncStorage in React-native

I'm trying to out some little cart system in my code then but I'm getting only one value in my cart. 我正在尝试在我的代码中输出一些小推车系统,但我的购物车中只有一个值。

For some reason, it seems like going to be an opening array into an array 出于某种原因,它似乎是一个数组的开放数组

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)

   });




  }

and then ı'm trying 然后我正在努力

    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>
        );
      }
     }

but it only shows the last object which I choose 但它只显示我选择的最后一个对象

Also I dont know how to remove that objects. 我也不知道如何删除这些对象。

You're saving your items as an array, but you're also getting these and putting them inside a new array. 您将项目保存为数组,但是您也可以将它们保存在新数组中。 Makes sense you only get the last item rendered because this may be the only item that's not inside another array. 理解你只获得最后一个项目,因为这可能是唯一不在另一个数组中的项目。 You can fix this by simply using the spread operator. 您可以通过简单地使用spread运算符来解决此问题。

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;
        });

Checkout the removeItem() method in the React Native Docs to remove items. 检查React Native Docs中removeItem()方法以删除项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM