简体   繁体   中英

What's wrong with my FlatList? react-native

My Flatlist does not work for me, Some one please review and give me a solution

const data = [
    'hai', 'hloooo'
]

class HotelList extends Component {

    render() {

        console.log('data==========', data)

        return (
                
                <View style = {{flex: 1, height: '100%', width: '100%'}}>
                    <Text>Hai</Text>
                    <FlatList 
                        data = {data}
                        keyExtractor = {(item, index) => index.toString()}
                        renderItem = {itemData => {
                            console.log(itemData)
                            return (
                                <View style = {{width: '100%', height: 100, flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'yellow'}}>
                                    <Text>Holaaaaaa</Text>
                                </View>
                            )
                        }} 
                    />
                </View>
        )
    }
}

export default HotelList

Basically you have missed some basic theory about how to use a flat list in react native. See official documentation here

Solution:

You need to add id to your array in order to make keyExtractor work

const data = [
  {
    id: "1",
    title: "First Item",
  },
  {
    id: "2",
    title: "Second Item",
  },
  {
    id: "3",
    title: "Third Item",
  },
];

class HotelList extends Component {
  render() {
    console.log("data==========", data);

    return (
      <View style={{ flex: 1, height: "100%", width: "100%" }}>
        <Text>Hai</Text>
        <FlatList
          data={data}
          keyExtractor={(item) => item.id}
          renderItem={(item) => {
            console.log(item);
            return (
              <View
                style={{
                  width: "100%",
                  height: 100,
                  flex: 1,
                  alignItems: "center",
                  justifyContent: "center",
                  backgroundColor: "yellow",
                }}
              >
                <Text>{item.title}</Text>
              </View>
            );
          }}
        />
      </View>
    );
  }
}

export default HotelList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM