【问题标题】:React grabbing JSON response propertyReact 抓取 JSON 响应属性
【发布时间】:2019-09-19 22:12:58
【问题描述】:

我对 React 很陌生。我有一个通过 WebAPI 2 返回给我的 JSON 响应。

我只想显示此回复的部分内容,例如,如果我只想显示标题

我已经实现了以下代码,但是当视图标题显示为未定义时

App.js

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {reply: ""}
    this.callAPI = this.callAPI.bind(this);
  }

  componentDidMount(){
    this.callAPI();
  }

  callAPI(){
    fetch('http://localhost:51092/api/COM',{
      method:'get',
      headers:{'Content-Type':'application/json'}
    }).then(function(response){
      return response.json();
    }).then(responseData => {
      this.setState({reply:responseData});
      console.log("REPONSEDATA-----"+responseData);
      console.log(responseData.title);
    });
  }

  render(){
    return(
      <div>
      </div>
    );
  }
}

更新 1

    callAPI(){
    fetch('http://localhost:51092/api/COM',{
      method:'get',
      headers:{'Content-Type':'application/json'}
    }).then(response =>{
      return response.json().then(responseData => {
        this.setState({reply:responseData});
        console.log("RESPONSE----"+JSON.stringify(responseData));
        console.log(responseData.title);
      });
    });
  }

API JSON 响应

[{
    "fileVer": {
        "type": "specific",
        "fileId": {
            "type": "specific",
            "internalId": 1,
            "externalId": null
        },
        "internalVersion": 2,
        "externalVersion": null,
        "versionSortKey": "0"
    },
    "title": "1576544 Alberta Ltd._Annual Returns_2012-01-03",
    "extension": "pdf",
    "logicalSize": "47872",
    "sizePrecision": "exact",
    "createdAtUtc": "2019-05-27T15:22:41.510Z",
    "lastAccessedAtUtc": "2019-07-10T21:00:28.029Z",
    "lastWrittenAtUtc": "2019-05-27T15:17:48.000Z",
    "changedAtUtc": "2019-05-27T15:17:48.000Z",
    "fileGuid": "{881D8975-84B9-4A73-9AFF-F0C61C94FE90}",
    "checksumMD5": "24f6badff8b70783697e0052fc4a7fe6",
    "fileMissing": false,
    "contentIsVolatile": false
}][{
    "fileVer": {
        "type": "specific",
        "fileId": {
            "type": "specific",
            "internalId": 2,
            "externalId": null
        },
        "internalVersion": 3,
        "externalVersion": null,
        "versionSortKey": "0"
    },
    "title": "1576544 Alberta Ltd._By-Law #1_",
    "extension": "pdf",
    "logicalSize": "951046",
    "sizePrecision": "exact",
    "createdAtUtc": "2019-05-27T15:22:42.000Z",
    "lastAccessedAtUtc": "2019-07-10T21:02:54.062Z",
    "lastWrittenAtUtc": "2019-05-27T15:16:28.000Z",
    "changedAtUtc": "2019-05-27T15:16:28.000Z",
    "fileGuid": "{F8B54DB0-7E9F-4F0F-8ABA-D03C1DE4FF8C}",
    "checksumMD5": "ffe728ef1a87f0cec7737b6d224bb50d",
    "fileMissing": false,
    "contentIsVolatile": false
}]

不确定我在这里做错了什么,我经常使用 Ajax,所以我可能会混淆 react 和 fetch 可以做什么

更新 2

所以看起来这可能是一个对象,而不是一个对象数组。

        console.log("RESPONSE----"+JSON.stringify(responseData));
        var arr = [];
        console.log("KEYS"+Object.keys(responseData));
        Object.keys(responseData).forEach(function(key){
          console.log(responseData[key]);
          arr.push(responseData[key]);

当我尝试访问 responseData[key] 时,我最终得到一个字母,而不是来自 json 响应的属性

这让我相信这不是一个对象数组而是一个对象

【问题讨论】:

  • responseData 的控制台日志显示什么?
  • 只需 console.log(responseData) 打印上面的 JSON 响应

标签: javascript json reactjs asp.net-web-api


【解决方案1】:

您应该在打印完整的 json 响应时使用 JSON.stringify 并且如果对象的一部分是字符串(例如... response.title 则可以,但如果不是,您可以尝试 .toString() 或 JSON.stringify)

        callAPI(){
            fetch('http://localhost:51092/api/COM',{
              method:'get',
              headers:{'Content-Type':'application/json'}
            }).then(function(response){
              return response.json().then((responseData)=>{
              this.setState({reply:responseData});
              console.log("REPONSEDATA----"+JSON.stringify(responseData));
              console.log(responseData.title);
              return responseData
              });

          }

【讨论】:

  • 添加JSON.stringify(responseData.title)仍然显示为未定义,至于字符串,responseData.title.toString()这会导致错误>未处理的拒绝(TypeError):无法读取未定义的属性'toString'
  • 你是对的,修正了评论,这应该可以工作
  • 我得到一个 App.js:25 Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined, will provide updated function in original question to track updates 我做了
  • then(function(response){改成箭头函数
  • 做到了,将在上面更新...仍然为response.title提供未定义
猜你喜欢
  • 2018-01-28
  • 2013-08-12
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多