繁体   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