【问题标题】:How to get a specific data from fetch api如何从 fetch api 获取特定数据
【发布时间】:2019-11-07 16:40:39
【问题描述】:

我正在尝试在我的 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"
        }
    },
.
.
.

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

【问题讨论】:

  • 在您的&lt;Text/&gt; 中替换为this.state.dataSource.length&gt;0 ? this.state.dataSource[1].name : "Loading Data"

标签: javascript json react-native fetch-api


【解决方案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>
   );
 }
}

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

【讨论】:

    【解决方案2】:

    如果问题是您的组件在请求完成后没有更新该属性,那是因为您正在对 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>
       );
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2017-05-26
      • 2019-03-25
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多