如何从带有条件的 React Native 中的 API 数组结果中获取记录?

Posted

技术标签:

【中文标题】如何从带有条件的 React Native 中的 API 数组结果中获取记录?【英文标题】:How to get a record from an array result of API in React Native with condition? 【发布时间】:2020-04-10 17:34:31 【问题描述】:

这是来自 API 的结果 JSON 文件:


    "data": [
        
            "recordid": "8888abc",
            "accountno": "00-00-00000-00007-00",
            "tag": "govid",
            "filename": "gov_id.png",
            "path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
            "ext": ".png",
            "posted_dt": "12/11/2019 10:38:20 AM"
        ,
        
            "recordid": "8888abc",
            "accountno": "00-00-00000-00007-00",
            "tag": "compid",
            "filename": "compid.jpg",
            "path": "C:\\MOBILEAPP\\compid/cid.jpg",",
            "ext": ".jpg",
            "posted_dt": "12/11/2019 10:38:20 AM"
        
    ],
    "error_message": "Successfully retrieved.",
    "is_success": true,
    "requested_on": "12/18/2019 2:14:27 PM"

我需要将 path where tag = 'govid' 放入变量中,因为它用于另一个 API 获取。

 async getProfilePhotoPath(token) 
     //membid is recordid
    let membid = await AsyncStorage.getItem(MEMBER_ID);
    let resp2 = await fetch("https://api/files",
      
        method: 'GET',
        headers: 
          "Authorization": "Bearer " + token,
          "MemberID": membid,
          'Content-Type': 'application/json;charset=UTF-8',
        ,
      ,
    )
      .then(resp2 => 
        let respImg = resp2.json();
        varImagePath = "should contain data.path where tag = 'govid'"
        console.log('This is respImg values',respImg)
        return respImg;
      )
      .catch(error => 
        alert('Error in resp2 imgpath!' + error);
      );
   

 async getProfilePhoto() 
    let token = await AsyncStorage.getItem(ACCESS_TOKEN);

    this.getProfilePhotoPath(token);

    let resp = await fetch("https://api/filepathtoimage", 
      headers: 
        "Authorization": "Bearer " + token,
        "ImagePath": varImagePath,
      
    )
    let respBlob = await resp.blob();
    let reader = new FileReader()
    reader.readAsDataURL(respBlob)
    reader.onload = () => 
      this.setState( imgsrc: reader.result )
    
  

console.log('This is respImg values',respImg) 返回:

  This is respImg values
Promise _40: 0, _65: 0, _55: null, _72: null
_40: 1
_65: 1
_55:
data: Array(2)
0: recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "govid", filename: "gov_id.png", path: "C:\\MOBILEAPP\\governmentid/gov_id.png", …
1: recordid: "8888abc", accountno: "00-00-00000-00007-00", tag: "compid", filename: "compid.jpg", path: "C:\\MOBILEAPP\\compid/cid.jpg", …
length: 2
__proto__: Array(0)
error_message: "Successfully retrieved."
is_success: true
requested_on: "12/18/2019 3:10:32 PM"
__proto__: Object
_72: null
__proto__: Object

如何为 varImagePath 赋值(在本例中应为 'C:\MOBILEAPP\governmentid/gov_id.png')?

【问题讨论】:

【参考方案1】:

resp2.json() 返回一个承诺。

.then(resp2 => resp2.json())
.then(jsonObject => 
  const data = jsonObject.data;
  const record = data.find(item => item.tag === 'govid');
  if (record) 
    varImagePath = record.path;
  
)

【讨论】:

这有效,但我无法让 getProfilePhoto() 读取 varImagePath。 你应该等待这个函数await this.getProfilePhotoPath(token);【参考方案2】:

只需使用过滤器:

let filterString = 'govid';
const result = arr.filter(f => f.tag == filterString);

一个例子:

let arr = [
      
          "recordid": "8888abc",
          "accountno": "00-00-00000-00007-00",
          "tag": "govid",
          "filename": "gov_id.png",
          "path": "C:\\MOBILEAPP\\governmentid/gov_id.png",
          "ext": ".png",
          "posted_dt": "12/11/2019 10:38:20 AM"
      ,
      
          "recordid": "8888abc",
          "accountno": "00-00-00000-00007-00",
          "tag": "compid",
          "filename": "compid.jpg",
          "path": "C:\\MOBILEAPP\\compid/cid.jpg",
          "ext": ".jpg",
          "posted_dt": "12/11/2019 10:38:20 AM"
      
  ]

  let filterString = 'govid';
  const result = arr.filter(f => f.tag == filterString);

  console.log(result);

更新:

在您的回复中:

then(resp2 => 
    let respImg = resp2.json();
    let arr = respImg.data;
    let filterString = 'govid';
    const result = arr.filter(f => f.tag == filterString);        
    return respImg;
  )

【讨论】:

我把它换成了 const varImagePath = arr.filter(f => f.tag =='govid');它在 resp2 imgpath 中警告错误! ReferenceError: arr 未定义

以上是关于如何从带有条件的 React Native 中的 API 数组结果中获取记录?的主要内容,如果未能解决你的问题,请参考以下文章

React Native - 带有条件的 OneSignal 推送通知概念设置

如何使用带有 cookie 的 React Native 的 WebSocket

React Native ScrollView - 如何从另一个子组件按钮滚动到子组件?

React-native:如何在 React-native 中使用(和翻译)带有 jsx 的 typescript .tsx 文件?

React Native 中的条件渲染问题

React Native 条件渲染不起作用