我如何根据项目的状态将项目填充和删除到数组中?

How do i fill and remove an item into an array depending on its state?

我正在开发 React Native Android 应用程序。

我正在从我的 API 接收数据(ID 和姓名)。现在我正在使用带有 MKIconToggle (react-native-material-kit) 的 ListView 来显示我的列表数据。 使用 MKIconToggle,我可以为显示的项目提供两种不同的状态(点击 = 颜色为黑色/未点击 = 灰色)。现在我想将点击项目的列表发送回我的服务器。但是我只是想不通如何将点击的项目放入数组或其他东西中,并且只将点击的项目发送到服务器。

我的带有 ListView 的 RenderMethod 如下所示:

<ListView
   dataSource={this.state.dataSource}
   renderRow={this.renderList}
   horizontal={true}
   renderHeader={this.renderHeader}
/>

渲染列表:

<View
    style={{justifyContent: 'flex-start', alignItems: 'center', padding: 10, flexDirection: 'column'}}>
     <MKIconToggle
          checked={this.state.initialChecked}
          onCheckedChange={()=>this._onIconChecked(data)}
          onPress={this._onIconClicked}
          style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
        <Text state_checked={this.state.checkedState}
                      pointerEvents="none"
                      style={styles.titleChecked}
                      numberOfLines={3}>{data.name}</Text>
        <Text pointerEvents="none"
                      style={styles.title}
                      numberOfLines={3}>{data.name}</Text>
     </MKIconToggle>
</View>

现在我应该在 _onIconChecked 中处理我点击的项目:

_onIconChecked: function (data) {

   // Put data.id into an array, if it way clicked (state is true)
   // If date.id is unclicked again, then remove from array

},

我希望我能清楚地解释我的问题,否则请告诉我。我是编程和编写 Whosebug issues/questions 的新手,所以如果我做错了什么,请给我提示。

根据您的信息,我必须做出一些假设才能回答您的问题。

现在我将假定该检查处理程序正确 returns 与您的项目数组中的 ID 相同的项目的 'id'。

所以假设你的数组是:

[{name: 'Luke', id: 1'}, {name: 'Darth', id: 2'}]

如果我点击 'Luke' _onIconChecked 将收到一个 data 对象,其中至少包含 id: 1

第二个假设是您在某个地方有一个数组,您可以在其中存储那些单击的项目。我只是将它放在您的组件之外,因为 MK 已经负责正确呈现选中的项目。所以:

var _checkedItems = []

var myComponent = React.create...

最后的假设是传递给 _onIconCheckeddata 对象还包含有关复选框状态的信息,因此 date.checked 为真或假。

所有这些项目的精确实现可能不同,但这是我可以解决的问题。

现在你可以做的是:

_onIconChecked: function (data) {
  var id = data.id;
  var checked = data.checked;

  var currentIndex = _checkedItems.indexOf(id)

  if(checked) {
    if(currentIndex == -1) { _checkedItems.push(id) }
    // the 'else' would mean the item is already in the array, so no need to add
  } else {
    if(currentIndex > -1) {
      // This means that the item is in the array, so lets remove it:
      _checkedItems.splice(currentIndex, 1) // This removes the id from the array.
    }
  }
}

您现在要做的是仅从您的 this.state.items 数组中获取其 ID 在选中的数组中的项目:

getCheckedItems: function() {
  return this.state.items.map(function(item) {
    if(_checkedItems.indexOf(item.id) > -1){
      return item
    }
  })
}

我不确定您的设置,所以我做了很多假设并且可能过度设计了一些东西,但这可能会让您朝着正确的方向前进。