【问题标题】:React native - add discovered ble devices to set, and add option to pickerReact native - 添加发现的 ble 设备进行设置,并为选择器添加选项
【发布时间】:2019-07-28 19:55:14
【问题描述】:

我在 react native 中使用 Picker。当屏幕打开时,设备会扫描 ble 设备,并将它们添加到状态中的devices 数组中。选择器应该对devices 数组中的每个值都有一个选项。

通常,我会这样做:

构造函数:

this.state = { devices: [] };

找到设备时:

let devices = this.state.devices;
devices.push(device.id);
this.setState({ devices: devices });

然后像这样执行 Picker:

<Picker>
  {(this.state.devices).map((item, index) => {
    return <Picker.item key={index} label={item} value={item} />;
  })}
</Picker>

这很好用,除了因为设备会不断地重新发现,它们最终会多次出现在数组中。这不仅没用,而且数组长度会一直增长,直到应用程序内存不足。

为了解决这个问题,我尝试使用一个集合,因为它不应该自动包含重复项:

构造函数:

this.state = { devices: new Set() };

找到设备时:

let devices = this.state.devices;
devices.add(device.id);
this.setState({ devices: devices });

选择器:

由于set没有map函数,所以我取了entry(一个迭代器),把它变成了一个数组,然后映射了:

<Picker>
  {Array.from(this.state.devices.entries).map((item, index) => {
    return <Picker.item key={index} label={item} value={item} />;
  })}
</Picker>

这个,不行。调试工具表明状态中的集合永远不会被添加,所以我认为这是问题所在(而不是选择器),但我不明白为什么会这样。

不会抛出任何错误。

【问题讨论】:

    标签: javascript arrays react-native set


    【解决方案1】:

    您可能需要先检查,然后再推入数组以避免重复条目,

    let devices = this.state.devices;
    if(devices.indexOf(device.id) == -1){
      devices.push(device.id);
      this.setState({ devices: devices });
    }
    

    这肯定不会推送已经处于状态的设备ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 2012-11-29
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      相关资源
      最近更新 更多