将数组作为要呈现的数据传递时,对象作为React子级无效

dnph8jn4  于 2023-01-31  发布在  React
关注(0)|答案(1)|浏览(108)

我正在使用一个名为react-native-autocomplete-input的依赖项。这里我尝试使用一个数组形式的数据集合。但是每次我尝试使用数组Objects are not valid as a React child. If you meant to render a collection of children, use an array instead时,它都会抛出错误。下面是我的代码:

return (
  <Autocomplete
      data={queryResult}
      placeholder={"Type name ..."}
      autoFocus={true}
      placeholderTextColor={'#fff'}
      keyExtractor={(item, i) => item.id.toString()}
      onChangeText={(text) => searchData(text)}
      renderItem={({ item, i }) => (
          <TouchableWithoutFeedback
              onPress={() => {
                  props.navigation.navigate("MovieDetail", {
                      item: item,
                  });
              }}
          >
              <View
                  style={{
                      flex: 1,
                      flexDirection: "row",
                      marginBottom: 10,
                      borderColor: 'red',
                      borderWidth: 1
                  }}
              >
                  <Image
                      style={{ width: 38, height: 57 }}
                      source={{ uri: 'https://picsum.photos/200' }}
                  />
                  <View
                      style={{
                          flexWrap: "wrap",
                          flexDirection: "column",
                          marginLeft: 5,
                          justifyContent: "center",
                      }}
                  >
                      <Text>New movie</Text>
                      <Text>2021</Text>
                  </View>
              </View>
          </TouchableWithoutFeedback>
      )}
  />
)

这是来自我的渲染函数。我传递queryResult作为抛出错误的数据。下面是我的queryResult数组的样子:

var queryResult = [
  {
    backdrop_path: "http://image.tmdb.org/t/p/w500//axMEROxH94BveBZBfPctWX4qLe4.jpg",
    genre_ids: [16, 878, 10751, 35],
    genres: undefined,
    id: 482321,
    image: "http://image.tmdb.org/t/p/w342//gA9QxSravC2EVEkEKgyEmDrfL0e.jpg",
    popularity: 1119.149,
    stat: "2021-10-15",
    title: "Ron's Gone Wrong",
    vote_average: 8.3,
    vote_count: 484
  },
  {
    backdrop_path: "http://image.tmdb.org/t/p/w500//axMEROxH94BveBZBfPctWX4qLe4.jpg",
    genre_ids: [16, 878, 10751, 35],
    genres: undefined,
    id: 482321,
    image: "http://image.tmdb.org/t/p/w342//gA9QxSravC2EVEkEKgyEmDrfL0e.jpg",
    popularity: 1119.149,
    stat: "2021-10-15",
    title: "Ron's Gone Wrong",
    vote_average: 8.3,
    vote_count: 484
  }
]

这背后的原因是什么?我应该如何传递这个数组?

z2acfund

z2acfund1#

在react-native-autocomplete-input中,它需要一个字符串数组,而您填充的是一个对象数组。
1.如果要使用默认平面列表呈现项,则必须将数据作为字符串数组传递。例如data = ["input 1", "input data 2]
1.如果要使用对象,请使用“flatListProps”
例如:

<Autocomplete
  data={queryResult}
  flatListProps={{
      keyExtractor: (_, idx) => idx,
      renderItem: ({ item }) => <Text>{item.title}</Text>,
  }} 
/>

相关问题