【问题标题】:mapping id from json response to key and use it for FlatList react-native将 id 从 json 响应映射到键并将其用于 FlatList react-native
【发布时间】:2017-07-11 08:26:11
【问题描述】:

我有一个来自 api 响应的 json,如下所示:

centres = [{
    id: 1,
    name: "DEF",
    },{
    id: 2,
    name: "ABC",
  }]

现在我想将上述数据填充到 FlatList 中

return(
  <View>
    <FlatList
      data={this.state.centres}
      renderItem={({item}) => <CentreComponent centre={item}/>}
    />
  </View>
);

但我不能执行上述操作,因为数据(中心)没有“关键”属性。

现在我可以遍历数组中的每个项目并添加一个属性“key”,它的值与 ID 相同。但我觉得这很有效。

有没有更好的方法将“id”列映射到“key”以呈现 FlatList

【问题讨论】:

标签: node.js key react-native-flatlist


【解决方案1】:

我可以看到这种情况发生的最快方法是遍历数组。

const centres = [{
    id: 1,
    name: "DEF",
  },{
    id: 2,
    name: "ABC",
}];

const newCentres = centres.map( ( item ) => ({ key: item.id, name: item.name }) );

console.log( JSON.stringify( newCentres ) )
// [{"key":1,"name":""},{"key":2,"name":""}]

【讨论】:

    【解决方案2】:

    尝试使用 keyExtractor 。请将您的代码更新为:

    return(
     <View>
      <FlatList
       data={this.state.centres}
       keyExtractor={(item, index) => item.id}
       renderItem={({item}) => <CentreComponent centre={item}/>}
      />
      </View>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2019-02-12
      • 2023-03-10
      • 2014-04-12
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多