2017-06-12 75 views
0

我的应用程序每次汽车改变价格时都会向用户发送通知。它使用每小时运行的代码完成。React-Native更新AsyncStorage项目

代码如下:

backgroundData(){ 
     BackgroundTimer.setInterval(() => { 

     AsyncStorage.getItem('key').then(JSON.parse).then(items => { 
      this.setState({value: items}); 
     }) 

     if(!this.state.value == 0 || !this.state.value == null){ 
      const promises = this.state.value.map((item, index) => 
      fetch(`URL/GetDetalhesViatura?CarID=${item[0]}`) 
      .then(response => response.json()) 
     ) 
      Promise.all(promises).then(viaturas => this.setState({viaturas: flatten(viaturas)})) 

      const newItem = [] 
      this.state.viaturas.map((item, index) => 
      newItem.push([item.Preco, item.CodViatura]), 
      this.setState({ stateArray: newItem }) 
     ) 

      const newItem2 = [] 
      this.state.value.map((item, index) => 
      newItem2.push([item[1], item[0]]), 
      this.setState({stateArray2: newItem2}) 
     ) 

      var results = new Array(); 
      //CODE TO CHECK ARRAYS FOR DIFFERENT PRICES 
      this.setState({results: results}) 

      if(!this.state.results == 0 || !this.state.results == null){ 
      const promises = this.state.results.map((item, index) => 
       fetch(`URL/GetDetalhesViatura?CarID=${item[1]}`) 
       .then(response => response.json()) 
      ) 
      Promise.all(promises).then(viaturas2 => this.setState({viaturas2: flatten(viaturas2)})) 

      this.state.viaturas2.map((item, index) => 
       PushNotification.localNotification({ 
       message: "Notification", 
       }) 
      ) 
      } 
     } else { 
      console.log('empty') 
     } 
     }, 9999999); 
    } 

首先,它需要去抓取我AsyncStorage当前数据。如果它有数据,则从API获取新数据,然后比较两个数据,如果有不同的价格,它会向用户发送通知。

问题是我需要用新价格更新每辆车的'key'(如果价格发生变化),或者应用程序将继续向用户发送通知。

回答

2

我无法得到我想要的东西与AsyncStorage,所以我不得不使用包装称为简单店:https://github.com/jasonmerino/react-native-simple-store

我不得不改变了很多代码,但后来我能够改变我的数据想要并保存它。

使用简单商店,它可以将每辆汽车保存在同一个钥匙中的单个阵列或对象上,这对操纵数据来说更加容易。