简体   繁体   中英

Access object in JSON array with this.state in React Native

I am having trouble displaying an object from an array. I want to display id from here:

    [  
   {  
      "id":"1",
      "imagename":"dog"
   },
   {  
      "id":"2",
      "imagename":"cat"
   },
   {  
      "id":"3",
      "imagename":"mouse"
   },
   {  
      "id":"4",
      "imagename":"deer"
   },
   {  
      "id":"5",
      "imagename":"shark"
   },
   {  
      "id":"6",
      "imagename":"ant"
   }
]

Here is my attempt:

fetch(`http://www.example.com/React/data.php` , {
   method: 'POST',
   headers: {
     'Accept': 'application/json',
     'Content-Type': 'application/json',
   }

  })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
        id: responseJson[0].id, <-- Attempt to try to get the id from responsejson.
        },function() {
          // In this block you can do something with new state.
        });
    })
    .catch((error) => {
      console.error(error);
    });

With this I got undefined is not a function . I am not getting what I am doing wrong or how to access this object.

 <FlatList

       data={ this.state.dataSource}

       ItemSeparatorComponent = {this.FlatListItemSeparator}


       renderItem={({item}) => <View>


       <Card>

         <View>


           <Text style={{marginTop: 30}}> {this.state.responseJson.id}</Text>


         </View>

       </Card>


       </View>


     }

     keyExtractor={(item, index) => index.toString()}

  />

Try the async/await method, you are getting an error because the data is not load and the render function is trying to load the data.

async componentDidMount() {
    await fetch(`http://www.example.com/React/data.php`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }

    }).then((response) => response.json()).then((responseJson) => {
        this.setState({
            isLoading: false,
            dataSource: responseJson,
            id: responseJson[0].id
        });
    }).catch((error) => {
        console.error(error);
    });
}

Or another approach is to add a loading preloader or spinner like this.

First import the package.

import { ActivityIndicator } from 'react-native';

Second change the render method

render() {
    if (isLoading) {
        return ( <
            View style = {
                [styles.container, styles.horizontal]
            } >
            <
            ActivityIndicator size = "large"
            color = "#0000ff" / >
            <
            /View>
        );
    }
    return (
        // Your render stuffs
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center'
  },
  horizontal: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 10
  }
})

If any issue please let me know

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