Доступ к объекту в массиве JSON с помощью this.state в React Native - PullRequest
0 голосов
/ 22 мая 2018

У меня проблемы с отображением объекта из массива.Я хочу отобразить id отсюда:

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

Вот моя попытка:

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);
    });

С этим я получил undefined is not a function.Я не понимаю, что я делаю неправильно или как получить доступ к этому объекту.

 <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()}

  />

1 Ответ

0 голосов
/ 23 мая 2018

Попробуйте метод async / await, вы получите сообщение об ошибке, потому что данные не загружены, а функция рендеринга пытается загрузить данные.

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);
    });
}

Или другой подход заключается в добавлении предзагрузчика загрузкиили прядильщик, как это.

Сначала импортируйте пакет.

import { ActivityIndicator } from 'react-native';

Затем измените метод рендеринга

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
  }
})

Если возникнет какая-либо проблема, сообщите мне

...