首页 > 解决方案 > 如何使用 react-native 从 API 获取嵌套对象

问题描述

我正在使用 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'
     }
});

标签: javascriptreactjsapireact-nativedictionary

解决方案


您将整个对象数组放入 Text 中,不会显示任何内容

您需要当前地图中的另一张地图:


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

推荐阅读