簡體   English   中英

將 JSON 響應對象添加到 React Native 中的 useState 數組/字典

[英]Add JSON response objects to useState array/dictionary in React Native

我有一個 function getSensors ,它首先獲取所有現有傳感器,然后調用getDataForSpecificSensor(sensor)

const [sensorData, setSensorData] = useState([])

function getSensors() {
        tensor.get('Sensorsid')
            .then(function (response) {
                setSensors(response.data)
                for (i = 0; i < sensors.length; i++) {
                    getSensorDataForSpecificSensor(sensors[i])
                }
            })
    }

function getSensorDataForSpecificSensor(sensorsid) {
        tensor.get("Sensorperiod/" + sensorsid + "/2")
            .then(function (response) {
                //Use setSensorData() to set the response to the matching sid(deviceid), create new if it doesn't exist
            })
            .catch(function (error) {
                console.log(error)
            })
    }

getDataForSpecificSensor返回的 JSON 如下所示:

[{"id":2568,"sid":"arduino01","temperatur":32.06,"zeit":"2021-12-26T20:52:39.981682"}]

我的問題是:我應該為此使用二維數組嗎? 一本字典? 如果要么我如何將響應僅添加到與 sensorData 匹配的 sid 中,如果不存在則創建一個新的? React Native 中的 useState 讓我更難掌握。

應該像這樣工作: 在此處輸入圖像描述

管理此數據的一種方法是使用 object,其鍵是sid ,值是該sid的數據點數組,如下所示:

{
  arduino01: [
    {temperatur: 1, "zeit":"2021-12-26T20:52:39.981682"}, 
    {temperatur: 2, "zeit":"2021-12-26T20:52:39.981682"}
  ],
  arduino02: [{temperatur: 3, "zeit":"2021-12-26T20:52:39.981682"}]
}

您可以像這樣更新 object:

const [sensorData, setSensorData] = useState({});

...

function getSensorDataForSpecificSensor(sensorsid) {
  tensor.get("Sensorperiod/" + sensorsid + "/2").then(function (response) {
    const key = response.data.sid;
    const newData = response.data.data;

    if(!sensorData[key]) {
      // when the sid doesn't exist yet, create new key value pair
      setSensorData(previous => {
        previous.key = [newData];
        return {...previous};
      });
    } else {
      //when the sid exist already, add the newData to the existing data points
      const newValueForKey = [...sensorData.key, newData];
      setSensorData(previous => {
        previous.key = newValueForKey;
        return {...previous};
      })
    }
  }).catch(function (error) {
      console.log(error)
  })
}

我認為像這樣安排數據確實使更新更容易一些。 如果要遍歷所有鍵值對,可以使用Object.entries()之類的方法將 object 轉換為數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM