繁体   English   中英

如何使用 react-native 从 API 获取嵌套对象

[英]How do get nested objects from an API with react-native

我正在使用 QOD API,我似乎无法从 Json 获取报价数据。 这是我到目前为止所拥有的。 我很确定我没有正确映射数据,因为数据记录正常。 (请参阅附图),但我似乎无法得到它。 我只需要作者和 imageUrl。 非常感谢任何帮助或指导。

在此处输入图像描述

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

您正在将整个 object 数组放入不会显示任何内容的文本中

您需要在当前 map 中再安装一个 map:


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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