简体   繁体   English

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

[英]How to get a specific data from fetch api

I am trying to get and show a specific data from api in a <Text> tag in my React Native app.我正在尝试在我的 React Native 应用程序的<Text>标记中获取并显示来自 api 的特定数据。 What I'm trying to do is to show the name of second object from that api.我要做的是从那个 api 中显示第二个 object 的名称。

Here is my code:这是我的代码:

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>
   );
 }
}

And the API:还有 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"
        }
    },
.
.
.

But I can't get the data I need.但我无法获得我需要的数据。 Any help would be appreciated任何帮助,将不胜感激

these data requests asynchronously, so when the first render occurs, there is no data returned from the 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>
       {
         this.state.dataSource.length === 0 ?
           <Text>Waiting moment.</Text> :
           <Text>{this.state.dataSource[1].name}</Text>
       }

     </View>
   );
 }
}

Making these changes you can visualize the data you need.进行这些更改后,您可以可视化所需的数据。

If the problem is that your component isn't updating the that property after the request is complete it is because you are doing a 'shallow merge' on the dataSource Array so React isn't able to detect changes to the data.如果问题是您的组件在请求完成后没有更新该属性,那是因为您正在对dataSource数组进行“浅合并”,因此 React 无法检测到数据的更改。 There are a few ways you can handle it:有几种方法可以处理它:

  1. Deep merge深度合并
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 https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action

  1. Pull the name property out to the top-level of you component statename属性拉到组件 state 的顶层
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>
   );
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM