【问题标题】:How to save an AsyncStorage to the state in the react native如何将 AsyncStorage 保存到 react native 中的状态
【发布时间】:2018-09-12 13:33:37
【问题描述】:

我是 react native 的新手,我正在开发一个餐厅应用程序。我想实施一个购买篮子!顾客选择食物并将食物添加到购物篮中。

现在我想将每种食物及其属性保存在 AsyncStorage 中,并将其放入购物篮组件中。我的食物及其属性是食物名称、食物编号、食物数量和食物成本。每种食物的关键是食物名称。 (AsyncStorage 的键)。

我想将食物数组保存在 AsyncStorage 中,然后将其放入篮子组件中,然后将 AsyncStorage 保存到 state。 这是我在 AsyncStorage 中保存数组的代码:

var key=this.state.myfoodName;
var info=[{id : myid,foodName : myfoodName, count : mycount, cost: mycost}];
var myjson=await JSON.stringify(info);
    await AsyncStorage.setItem(key , myjson);

在购物篮组件中,我想将 AsyncStorage 保存到状态! 这样做的代码是:

componentDidMount(){
    AsyncStorage.getAllKeys((err, keys) => {
        keys.map((key,keys)=>{
            AsyncStorage.getItem(key,(error,result)=>{
                    let myresult= JSON.parse(result);
                    console.warn(myresult);  // each key is a food that customer has added to the basket.and i want to save each that to the state.
                    this.setState({

                    baskets: myresult
                    });


            });

            })});

篮子状态是:

baskets:[{
            id:'',
            foodName:'',
            count:0,
            cost:''
        }]

在平面列表中,我显示购物篮状态。

问题:

1-当我运行此代码时,我看不到购物篮列表!现在我想知道我哪里出错了?我认为我的数组不正确。

2-我无法将所有异步存储保存到购物篮状态。我怎样才能做到这一点? 例如,我们的客户在篮子中添加了 2 种食物。如何将篮子状态中的所有食物保存并显示出来?

提前感谢。

【问题讨论】:

  • 您似乎只向 AsyncStorage 添加了一项。在这种情况下,很难保存所有项目。所以我认为当你添加一个新项目时,首先从 AsyncStorage 中获取现有项目,并将它们与新项目合并,最后,你需要保存它们。
  • 您可以使用JSON.stringify(value)将其存储到任何密钥并使用JSON.parse检索它

标签: react-native


【解决方案1】:

您可以拥有一个名为 basket 的数组类型的键。 在购物篮中添加商品:-

  1. 从 asyncstorage 中获取购物篮数组。
  2. 将项目推送到购物篮阵列。
  3. 更新 asyncstorage 中的购物篮数组。

async addItemToBasket(item) {
  let basketItems = await this.getBasketItems();
  console.log("Current basket", basketItems);
  basketItems.push(item);
  console.log("Updated basket", basketItems);
  await AsyncStorage.setItem(
    "basket", 
    JSON.stringify(basketItems)
  );
}

async getBasketItems() {
  let currentBasket = await AsyncStorage.getItem("basket");
  console.log("currentBasket", currentBasket);
  return currentBasket ? JSON.parse(currentBasket) : [];
}
   
// calling addItemToBasket to add item.
this.addItemToBasket({
  id: "345",
  foodName: "pizza",
  count: 1,
  cost: "150"
});

this.addItemToBasket({
  id: "346",
  foodName: "Burger",
  count: 2,
  cost: "100"
});


// calling getBasketItems
componentDidMount() {
  this.getBasketItems()
  .then((basket)=> this.setState({basket: basket}))
   /* here basket will be:  
     [{ id: "345",
        foodName: "pizza",
        count: 1,
        cost: "150"
      },
      {
        id: "346",
        foodName: "Burger",
        count: 2,
        cost: "100"
      }]
    */
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多