如何从提取api获取特定数据

问题描述 投票:-1回答:1

我正在尝试在我的React Native应用程序的<Text>标签中从api获取并显示特定数据。我想做的是显示该api中第二个对象的名称。

这是我的代码:

class HomeSreen extends Component {
 constructor(props) {
   super(props);
   this.state = {
     dataSource: [],
   };
 }
 componentDidMount() {
   const request = new Request('http://jsonplaceholder.typicode.com/users');

   fetch(request)
     .then(response => response.json())
     .then(responseJson => {
       this.setState({
         dataSource: responseJson,
       });
     });
 }
 render() {
   return (
     <View>
       <Text>Home Screen</Text>
       <Text>{this.state.dataSource[1].name}</Text>
     </View>
   );
 }
}

和API:

[

    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "[email protected]",
        "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
                "lat": "-37.3159",
                "lng": "81.1496"
            }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        }
    },
    {
        "id": 2,
        "name": "Ervin Howell",
        "username": "Antonette",
        "email": "[email protected]",
        "address": {
            "street": "Victor Plains",
            "suite": "Suite 879",
            "city": "Wisokyburgh",
            "zipcode": "90566-7771",
            "geo": {
                "lat": "-43.9509",
                "lng": "-34.4618"
            }
        },
        "phone": "010-692-6593 x09125",
        "website": "anastasia.net",
        "company": {
            "name": "Deckow-Crist",
            "catchPhrase": "Proactive didactic contingency",
            "bs": "synergize scalable supply-chains"
        }
    },
.
.
.

但是我无法获得所需的数据。任何帮助,将不胜感激

javascript json react-native fetch-api
1个回答
0
投票

我认为您要访问特定的用户数据。但是http://jsonplaceholder.typicode.com/users返回所有用户列表。因此,您必须发送想要访问的用户ID,例如

http://jsonplaceholder.typicode.com/users/2

它将为您提供数组的第二个用户。

{
  "id": 2,
  "name": "Ervin Howell",
  "username": "Antonette",
  "email": "[email protected]",
  "address": {
    "street": "Victor Plains",
    "suite": "Suite 879",
    "city": "Wisokyburgh",
    "zipcode": "90566-7771",
    "geo": {
      "lat": "-43.9509",
      "lng": "-34.4618"
    }
  },
  "phone": "010-692-6593 x09125",
  "website": "anastasia.net",
  "company": {
    "name": "Deckow-Crist",
    "catchPhrase": "Proactive didactic contingency",
    "bs": "synergize scalable supply-chains"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.