目的是引入嵌套数组“记录”。我的当前输出在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": "[email protected]",
      "author": "Clu",
      "Contractor Name": "Just say no to love!!",
      "avatarUrl": "https://placeimg.com/200/240/any"
    },{
      "id": 2,
      "email": "[email protected]",
      "author": "Anne Droid",
      "Contractor Name": "I wanna know what love is...",
      "avatarUrl": "https://placeimg.com/200/240/any"
    }
  ]
 }
}


javascript -  react 对象内的 map 嵌套数组-LMLPHP

最佳答案

_fetchRecords函数需要更改为:-

_fetchRecords() {
  $.ajax({
   method: 'GET',
   url: 'http://apidata:8888/data.json',
   success: (results) => {
     this.setState({ results: results.result.records });
   },
   error: () => {
     console.log('error');
   }
  });
 }

09-07 13:14