【问题标题】:React map nested array within object在对象中反应映射嵌套数组
【发布时间】:2017-06-14 20:02:27
【问题描述】:

目标是拉入嵌套数组“记录”。我当前的输出在反应控制台中显示数组,但有错误。我会尽量简洁,但会尽量简短。

错误屏幕有 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"
    }
  ]
 }
}

【问题讨论】:

  • 为什么_getRecords在课外?
  • 您在this.state.results 中存储了什么以及何时存储?
  • @arkjoseph 你如何调用 _getRecords 以及从哪里调用?
  • 您是否将.(this) 绑定到_getRecords 函数?
  • @arkjoseph 检查我发布的答案。它应该可以解决您的问题。

标签: javascript json reactjs ecmascript-6


【解决方案1】:

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

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

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

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

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

我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    _fetchRecords 函数需要改为:-

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

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 2021-12-11
      • 2021-02-08
      • 2023-01-23
      • 2021-09-30
      相关资源
      最近更新 更多