javascript - React 映射对象内的嵌套数组

标签 javascript json reactjs ecmascript-6

目标是拉入嵌套数组“记录”。我当前的输出显示 react 控制台中的数组,但有错误。我会尝试尽可能简洁,但会保持简短。

错误屏幕有 3 行引用 _getRecords,因此我确信 _getRecords 是有问题的子项。

class RecordBox extends Component {
    constructor() {
    super();

  this.state = {
    showComments: false,
    results: []
  };
 }
 render(){
   const records = this._getRecords();
   return (
      // jsx template code...
   );
  }
  // API Call
 _fetchRecords() {
  $.ajax({
   method: 'GET',
   url: 'http://apidata:8888/data.json',
   success: (results) => {
     this.setState({ results });
   },
   error: () => {
     console.log('error');
   }
  });
 }
 _getRecords() {
    // TypeError: this.state.results.map is not a function...
    return this.state.results.map((record) => {
      return <Comment body={record["Contractor Name"]} />
    });
  }
}

我有一个如下所示的提要。我无权修改此内容。

{
"result": {
  "records": [
    {
      "id": 1,
      "email": "clu.hey@gmail.com",
      "author": "Clu",
      "Contractor Name": "Just say no to love!!",
      "avatarUrl": "https://placeimg.com/200/240/any"
    },{
      "id": 2,
      "email": "hello@gmail.com",
      "author": "Anne Droid",
      "Contractor Name": "I wanna know what love is...",
      "avatarUrl": "https://placeimg.com/200/240/any"
    }
  ]
 }
}

REACT Console

最佳答案

我认为您只是没有将状态设置为正确的值。您的 state.results 当前是一个对象。只需确保在设置状态时将 state.results 设置为 results.result.records

this.setState({ results: results.result.records })

您还可以做的一件事是将结果直接映射到 jsx 代码中并跳过使用 _getRecords 函数。

<div>
   {
     this.state.results.map( ( record ) => {
       return <Comment />
     }
   }
</div>

这是我通常写的方式,因为这样更容易阅读,但这是个人喜好。

希望这会有所帮助!

关于javascript - React 映射对象内的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553757/

相关文章:

javascript - 如何将jQuery中的输入类型传递给ajax

javascript - 尝试发送数据时,放大的弹出页面恢复为原始格式

javascript - 无法从 json 中提取键/值

reactjs - 在 React Router 中设置相对路径

javascript - FontAwesome [Webpack] 未加载

javascript - FullPage.js 链接导航 <li> 滑动

json - Golang API 编码问题

java - 如何获取 json 数组中 json 子级的字符串

Python 请求发布包含 nan 的 json

javascript - 定期触发 React 效果