2017-06-12 76 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

我不得不改變了很多代碼,但後來我能夠改變我的數據想要並保存它。

使用簡單商店,它可以將每輛汽車保存在同一個鑰匙中的單個陣列或對象上,這對操縱數據來說更加容易。