对象数组循环中的循环

问题描述 投票:2回答:3

我的数据有一个JSON文件:

{
  "EIC": {
    "id": "EIC",
    "text": "Want to do a quick word game?",
    "replies": ["Sure", "Later"]
  },
  "YMB": {
    "id": "YMB",
    "text": "Okay, tomorrow. Cya!",
    "replies": ["bye Woebot"],
  }
}

我想呈现回复数组,以便我们可以在HTML中看到可能的不同答案。 这是我目前的组成部分:

import React from 'react';
import axios from 'axios';
import style from "../styles/entry.css";

import * as allornothing from '../allornothing.json';

class EntryList extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      list: Object.values(allornothing)
    }
  }

  renderReplies(replies) {
    return replies.map((reply) => {
        return (
            <div class="entry-body col-12">
                <button class="back">{ reply }</button>
            </div>
        )
    })
  }

  render() {
    return (
      <div class="row" id="entries-list">
        {this.state.list.map(function(entry) {
          return (
            <div class="col-md-4 col-sm-12">
              <div class="entry col-12">
                <div class="row">
                  <div class="entry-header col-12">
                    <div class="entry-id">
                      <span>{entry.id}</span>
                    </div>
                    <p>{entry.text}</p>
                  </div>

                  { this.renderReplies(entry.replies) }

                  <div class="entry-manage col-12">
                    <div class="row">

                      <span class="manage-button">
                        <i class="fas fa-comments"></i> Add new answer
                      </span>

                      <span class="manage-button">
                        <i class="fas fa-pencil-alt"></i> Modify
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>
    )
  }
}

export default EntryList

但我得到这个错误:

TypeError:无法读取未定义的属性'renderReplies'

然而,如果我用{ this.renderReplies(entry.replies) }替换console.log(entry.replies),它会打印每个问题的回复。在提出this solution函数之前我也尝试了renderReplies,但我得到同样的错误...... 此外,如果我将{entry.replies}放在我的html代码中,它也会渲染一个字符串列表。

有没有人知道为什么我会收到此错误以及如何显示我的回复列表?谢谢。

javascript arrays reactjs loops
3个回答
1
投票
{this.state.list.map(function(entry) {

将其更改为箭头功能。箭头函数从定义它们的上下文中获取this的值,这意味着函数this将继续作为你的组件

{this.state.list.map((entry) => {

1
投票

我认为你的问题可能没有将函数绑定到类。尝试将以下代码行添加到构造函数中:

this.renderReplies = this.renderReplies.bind(this)

或者,您可以使用箭头函数来维护“this”的上下文。看起来像这样:

renderReplies = replies => { ... }

0
投票

这很可能是因为this.renderReplies被称为function(){},它超越了this。您可以使用箭头函数来避免这种情况:

this.state.list.map(entry => {
...
{ this.renderReplies(entry.replies) }
...
});

你可以在箭头函数this上阅读更多关于here的内容

© www.soinside.com 2019 - 2024. All rights reserved.