React-Native 更新 AsyncStorage item

React-Native update AsyncStorage item

每当汽车更改价格时,我的应用程序都会向用户发送通知。它是通过每小时运行一次的代码完成的。

代码如下:

  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'(如果价格发生变化),否则应用会不断向用户发送通知。

我无法通过 AsyncStorage 获得我想要的东西,所以我不得不使用一个名为 simple-store 的包装器:https://github.com/jasonmerino/react-native-simple-store

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

使用简单存储,它将每辆汽车保存在同一个键中的单独数组或对象上,这更容易操作数据。