How to pass a list with objects from Server to FlatList?

故事扮演 提交于 2019-12-24 18:47:03

问题


I'm trying to create a FlatList that contains an array with objects that has an array from a server and I can't get it to work.

my error message:

TypeError: Cannot read proparty 'Data' of undefined

I can get it to work with my normal list that's not fetched from a Server. Heres the structure from my working list

[{"DATA":[{"filter_id":"44","filter_name":"filter 1"}, {"filter_id":"45","filter_name":"filter 2"},{"filter_id":"46","filter_name":"filter 3"},{"filter_id":"47","filter_name":"filter 4"},{"filter_id":"48","filter_name":"filter 5"}],"MESSAGE":"DATA FOUND","STATUS":200}]

My server list have the same structure but different values of filter_name and filter_id

here's my code:

constructor(props){
    super(props); 
    this.state = {
    data: [],
    oldData: [{"DATA":[{"filter_id":"44","filter_name":"filter 1"},{"filter_id":"45","filter_name":"filter 2"},{"filter_id":"46","filter_name":"filter 3"},{"filter_id":"47","filter_name":"filter 4"},{"filter_id":"48","filter_name":"filter 5"}],"MESSAGE":"DATA FOUND","STATUS":200}],
    page:1,
    status: null,
    isLoading: false,
    }
}
getData = async () => {
const url = 'http://ollenorstrom.se/ollenorstrom.se/avoka/api/getFilter.php?page='+this.state.page+'&row_per_page=5';
fetch(url).then((response) => response.json())
.then((responseJson) => {
   this.setState({
    data:this.state.data.concat(responseJson),
    isLoading:false
   });
})
}
componentDidMount() {
  this.getData();
}
renderRow = ({item}) => {
  console.log('item', item);
  return (
   <View style={styles.item}>
    <Text>{item.filter_name}</Text>
   </View>
  )
}
render() {
   console.log('state', this.state.data[0]);
   console.log('oldstate', this.state.oldData[0]) // this 
   return (
    <View style={styles.container}>
     <FlatList 
      data={this.state.data[0].DATA}
      renderItem={this.renderRow} 
      keyExtractor={(item, index) => index.toString()}
      />
     </View>
  );
}

Expo: https://snack.expo.io/@thesvarta/tenacious-sandwich


回答1:


The issue is that on the initial rendering of your component this.state.data is empty, because we have to wait until getData returns any data. That's why you cannot access this.state.data[0].DATA at the beginning.

The solution is to update your getData function a little bit.

getData = async () => {
    const url = 'http://ollenorstrom.se/ollenorstrom.se/avoka/api/getFilter.php?page='+this.state.page+'&row_per_page=5';
    fetch(url).then((response) => response.json())
    .then((responseJson) => {
      // here we save the data, we want to access later. 
      console.log('responseJson', responseJson[0].DATA);
       this.setState({
        data:this.state.data.concat(responseJson[0].DATA),
        isLoading:false
       });
    })
  }

Now your data is directly stored in this.state.data. We now can simplify your render() function:

 <FlatList 
       data={this.state.data} // simplified, passing an empty array at the beginning is ok
       renderItem={this.renderRow} 
       keyExtractor={(item, index) => index.toString()}
      />

Working example:

https://snack.expo.io/HJ--GFlnN



来源:https://stackoverflow.com/questions/56044935/how-to-pass-a-list-with-objects-from-server-to-flatlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!