以本机方式呈现JSON数据

时间:2018-05-21 05:35:16

标签: ruby-on-rails react-native

我正在使用我的api渲染JSON中的所有帖子以反应原生。但我一直得到这个未定义的错误。有时数据不会呈现。任何人都可以给我任何帮助,以反应原生渲染这些数据?并向我解释我做错了什么?我对JSON很新。谢谢:))

这是我的JSON:

{"data":[{"id":"1","type":"posts","links":{"self":"https://example.com/posts/1"},"attributes":{"title":"Laughter Post","context":{}},"relationships":{"user":{"links":{"self":"https://example.com/posts/1/relationships/user","related":"https://example.com/posts/1/user"}}}}]}

这是我的反应原生代码:

import React, { Component } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";

export default class App extends Component {
state = {
data: []
};

componentWillMount() {
this.fetchData();
}

fetchData = async () => {
const response = await fetch("https://example.com/posts.json");
const json = await response.json();
this.setState({ data: json.data });
};

render() {
  return (
    <View style={styles.container}>
     <FlatList
      data={this.state.data}
      keyExtractor={item => item.toString()}
      renderItem={({ item }) =>
        <Text>
          {`${item.title}`}
        </Text>}
       />
    </View>
   );
  }
 }

 const styles = StyleSheet.create({
 container: {
 marginTop: 15,
 flex: 1,
 justifyContent: "center",
 alignItems: "center",
 backgroundColor: "#F5FCFF"
 }
 });

1 个答案:

答案 0 :(得分:1)

您似乎直接从根访问title,但它位于密钥attributes

应该是

{`${item. attributes.title}`}

如果您能告诉我们确切的错误,我们可以帮助您解决此问题。