使用对象数组显示FlatList(React Native)

aurhwmvo  于 2023-03-03  发布在  React
关注(0)|答案(1)|浏览(123)

我有个 prop

console.log(this.props.userList);

退货

Array [
  Object {
    "userData": Object {
      "userName": "David",
      "userAge": 20,
    },
    "id": "ax3",
  },
  Object {
    "userData": Object {
      "userName": "Phillip",
      "userAge": 27,
    },
    "id": "xq4",
  },
  Object {
    "userData": Object {
      "userName": "Kelly",
      "userAge": 28,
    },
    "id": "pj7"
  }
]

我正尝试通过编写以下内容从该数据生成一个平面列表:

<FlatList
  data={this.props.userList}
  keyExtractor={item => item.id}
  renderItem={({ item }) =>
    <Text>{item.userData.userName}</Text>
  }
/>

在我的iPhone上测试Expo时,应用程序只是冻结。没有抛出任何错误或任何东西。这个方法不正确吗?

  • 添加以下完整渲染
render() {
    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <View style={styles.mainViewStyle}>
                <View style={styles.searchBarViewStyle}>
                    <TextInput
                        style={styles.textInputStyle}
                        placeholder="User"
                        autoCorrect={false}
                        autoCapitalize="none"
                        onChangeText={this.onUserChanged.bind(this)}
                        value={this.props.userInput}
                    />
                </View>
                <View>
                    <Button
                        title="press this"
                        onPress={() =>
                            this.props.navigation.navigate("yearSearch")
                        }
                    />
                </View>
                <View>
                    <Button
                        title="testUserSearch"
                        onPress={() => this.showData()}
                    />
                </View>
                <View>
                    <FlatList
                        data={this.props.userList}
                        keyExtractor={item => item.id}
                        renderItem={({ item }) => (
                            <Text>{item.userData.userName}</Text>
                        )}
                    />
                </View>
            </View>
        </TouchableWithoutFeedback>
    );
}

如果去掉Flatlist部分,它运行得很好,showData()函数目前只是控制台记录这个.props.userList,它在开头返回数组post。

7tofc5zh

7tofc5zh1#

你可以flatten你的对象数组in one array(place all objects in one array after receiving using some loop)然后在flat list中使用它(因为你知道每个对象有多少条目). to understanding it further see the correct answer here. react native flatlist with several arrays of data

相关问题