繁体   English   中英

React-native中的AsyncStorage存在问题

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

我正在尝试在我的代码中输出一些小推车系统,但我的购物车中只有一个值。

出于某种原因,它似乎是一个数组的开放数组

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

但它只显示我选择的最后一个对象

我也不知道如何删除这些对象。

您将项目保存为数组,但是您也可以将它们保存在新数组中。 理解你只获得最后一个项目,因为这可能是唯一不在另一个数组中的项目。 您可以通过简单地使用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;
        });

检查React Native Docs中removeItem()方法以删除项目。

暂无
暂无

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

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