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

时间:2019-11-07 16:40:39

标签: javascript json react-native fetch-api

我试图在我的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": "Sincere@april.biz",
        "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": "Shanna@melissa.tv",
        "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"
        }
    },
.
.
.

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

2 个答案:

答案 0 :(得分:1)

这些数据是异步请求的,因此,在首次渲染时,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>
       {
         this.state.dataSource.length === 0 ?
           <Text>Waiting moment.</Text> :
           <Text>{this.state.dataSource[1].name}</Text>
       }

     </View>
   );
 }
}

进行这些更改后,您可以可视化所需的数据。

答案 1 :(得分:0)

如果问题是请求完成后您的组件没有更新那个属性,那是因为您在dataSource数组上进行了“浅合并”,因此React无法检测到更改数据。有几种处理方法:

  1. 深度合并
fetch(request)
    .then(response => response.json())
    .then(responseJson => {
      this.setState(prevState => {
        return {
          ...prevState.dataSource,
          dataSource: responseJson.map((obj, i)=>{ return {...dataSource[i], ...obj}},
        }
      });
    });

https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action

  1. name属性拉到组件状态的顶层
class HomeSreen extends Component {
 constructor(props) {
   super(props);
   this.state = {
     dataSource: [],
     screenTitle
   };
 }
 componentDidMount() {
   const request = new Request('http://jsonplaceholder.typicode.com/users');

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