【问题标题】:How do get nested objects from an API with react-native如何使用 react-native 从 API 获取嵌套对象
【发布时间】:2020-05-28 11:19:40
【问题描述】:

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

【问题讨论】:

  • 你在寻求什么样的帮助?
  • 如果想获取作者试试 console.log(data[0].author);作为 console.log(data) 下的另一个日志
  • 对不起,我可以记录数据,但我无法显示它
  • 如果您获得所需的数据,您可以在控制台日志之后设置状态,例如: this.setState({ author: data[0].author )} 确保您有 author = "" 或author = 您所在州的 null。

标签: javascript reactjs api react-native dictionary


【解决方案1】:

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

您需要在当前地图中添加另一张地图:


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多