【问题标题】:Updating nested object inside react native state without manipulating whole object在不操作整个对象的情况下更新反应本机状态的嵌套对象
【发布时间】:2020-05-14 10:14:56
【问题描述】:

我正在做一个 react native 项目

这是我在反应类组件构造器中初始化的状态变量

this.state = {
      region: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      markers: [],
      geoJson: null,
      geoJsonLoading: true,
      usertoken: "",
      featureChanges: null,
      socketConnectionError: "",
    };

在 geoJson 状态变量中,我以以下格式存储数据

{
  type: 'FeatureCollection',
  features: [
    {
      userid: 'c5d84a8a-e7ec-465a-b01c-d7a9e702aed2',
      type: 'Feature',
      properties: {},
      geometry: [Object]
    },
    {
      userid: '7ccb05de-6e71-4862-b1f5-a61b134d99ef',
      type: 'Feature',
      properties: {},
      geometry: [Object]
    },
    ...
  ]
}

这是我们在任何更新或从服务器新创建时收到的对象的形状。

{
      userid: '7ccb05de-6e71-4862-b1f5-a61b134d99ef',
      type: 'Feature',
      properties: {},
      geometry: [Object]
    }

现在,当我们从服务器收到任何新的或更新的功能对象时,我想立即在状态内添加/更新该功能并重新渲染组件以在 MapView 上显示更新的功能。

我不想一次又一次地创建整个 geoJson,因为它存储了许多特征,并且重复重新计算整个数据集可能会很昂贵。我只想更新需要更新的特定特征。

我尝试了很多东西,但都没有奏效。 请帮忙。

【问题讨论】:

  • 你说的“我不想一次又一次地创建整个geoJson”是什么意思,你的意思是一个新的网络调用?
  • 我想要的是,在组件安装时首先用实际数据初始化geoJson,然后我只想添加/更新我们从服务器的连续流中接收到的特定功能。

标签: reactjs react-native state native geojson


【解决方案1】:

当您收到来自服务器流的新对象时,请尝试更新 geoJson,如下所示。

this.setState({geoJson:{...this.state.geoJson, features:[...this.state.geoJson.features,newObjectFromServer]})

【讨论】:

  • 显示错误:undefined is not an object (evaluating 'features.filter')
猜你喜欢
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2019-02-03
  • 1970-01-01
相关资源
最近更新 更多