簡體   English   中英

如何從獲取 api 中獲取特定數據

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

我正在嘗試在我的 React Native 應用程序的<Text>標記中獲取並顯示來自 api 的特定數據。 我要做的是從那個 api 中顯示第二個 object 的名稱。

這是我的代碼:

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"
        }
    },
.
.
.

但我無法獲得我需要的數據。 任何幫助,將不勝感激

這些數據是異步請求的,所以當第一次渲染發生時,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>
   );
 }
}

進行這些更改后,您可以可視化所需的數據。

如果問題是您的組件在請求完成后沒有更新該屬性,那是因為您正在對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屬性拉到組件 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