首页 > 解决方案 > 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>
        );
      }
     }

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

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

标签: javascriptreactjsreact-nativeasyncstorage

解决方案


您将您的项目保存为一个数组,但您也得到了这些并将它们放入一个新数组中。有意义的是,您只得到最后一个呈现的项目,因为这可能是唯一不在另一个数组中的项目。您可以通过简单地使用扩展运算符来解决此问题。

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()中的方法以删除项目。


推荐阅读