Как получить вложенные объекты из API с помощью react-native - PullRequest
0 голосов
/ 28 мая 2020

Я использую QOD API и не могу получить данные цитаты из Json. Вот что у меня есть на данный момент. Я почти уверен, что не отображаю данные должным образом, поскольку данные записываются нормально. (См. Прикрепленное изображение), но я просто не могу его понять. Мне просто нужен автор и imageUrl. Любая помощь или направление приветствуются.

enter image description here

    export default class QuoteScreen extends React.Component {
         constructor(props) {
              super(props);
              this.state = {
                   loading: true,
                   data: null,
                   error: null,
              };
     }
     apiUrl = 'https://quotes.rest/qod';

     getData = (ev) => {
          this.setState({ loading: false, error: null });
          let h = new Headers();
          h.append('X-TheySaidSo-Api-Secret', '*******************My API key');
          let req = new Request(this.apiUrl, {
               headers: h,
               method: 'GET',
          });
          fetch(req)
               .then(response => response.json())
               .then(this.showData)
               .catch(this.ErrorMessage);
     };
     showData = (data) => {
          this.setState({ loading: true, data });
          console.log(data);
     };
     ErrorMessage = (err) => {
          this.setState({ loading: true, error: err.message });
     };
     componentDidMount() { }

     render() {
          return (
               <View styles={styles.container}>
                    {!this.state.loading && <Text>Loading</Text>}
                    <Text style={styles.txt}>Gimme Some Data</Text>
                    <Button title="GetData" onPress={this.getData} />
                    {this.state.error && (<Text style={styles.err}>{this.state.error}</Text>
                    )}

                    {this.state.data && this.state.data.length > 0 && (
                         this.state.data.map((contents) => (

                              <Text style={style.txt}>{contents.quotes}</Text>
                         ))
                    )}
               </View>
          );
     }
}
const styles = StyleSheet.create({
     container: {
          flex: 1,
          backgroundColor: '#F4C724',
     },
     txt: {
          fontSize: 24,
          color: '#333'
     },
     err: {
          color: 'red',
          fontSize: 30,
          fontWeight: 'bold'
     }
});

1 Ответ

0 голосов
/ 28 мая 2020

Вы помещаете весь массив объектов в текст, который ничего не отображает

Вам нужна другая карта внутри текущей карты:


!!contents.quotes?.length && 
contents.quotes.map(quote=>{
 return <Text style={style.txt}>{quote.author}</Text>
 }                   
...