【问题标题】:Rendering Nested Objects in Reactjs在 Reactjs 中渲染嵌套对象
【发布时间】:2017-05-19 10:20:49
【问题描述】:

我正在关注 Meteor/Reactjs 教程。我有一个我们称之为苹果的项目列表,以及一个名为橙色的项目子列表。

orange 集合中的每个orange 都有一个“appleId”字段,该字段映射到关联Apple 的_id。

目前我所拥有的并不能如我所愿。理想的列表应该呈现为:

  • 苹果 1
    • 橙色 1A
    • 橙色 1B
  • 苹果 2
    • 橙色 2A
    • 橙色 2B

我使用这些功能:

renderApples() {
  return this.props.apples.map((apple) => (
    <Apple key = {apple._id} apple={apple) />
  ));
}
renderOranges() {
  return this.props.oranges.map((orange) => (
    <Orange key = {orange._id} orange={orange) />
  ));
}

然后像这样在我的主要组件中调用它们:

render() {
  return (
  <div>
    <ul>
      {this.renderApples()}
    </ul>
    <ul>
      {this.renderOranges()}
    </ul>
  );
}

这显然只是渲染了所有的苹果,然后是所有的橙子,但我一直很难找到一种聪明的方法来渲染它们。

【问题讨论】:

  • 您的数据格式似乎不正确,因为我不知道您如何知道哪些橙子与哪些苹果相关联。

标签: mongodb reactjs meteor


【解决方案1】:

如果数据关系如你所说,那不是苹果渲染器的责任也要渲染橙子吗?

例如

renderApples() {
  return this.props.apples.map((apple) => (
    <Apple key={apple._id}
        apple={apple}
        oranges={Oranges.find({appleId: apple._id}).fetch()} />
  ));
}

更新:

然后 Apple 组件会负责显示与每个苹果相关的橙子。例如

import React, {Component, PropTypes} from 'react';

export class Apple extends Component {
    constructor(props) {
        super(props);
    }

    renderOranges() {
        return this.props.oranges.map((orange) => (
            <Orange key={orange._id} orange={orange} />
        ));
    }

    render() {
        return (
            <div>
                <h1>I'm an Apple! {this.props.apple._id}</h1>
                <ul>
                    {this.renderOranges()}
                </ul>
            </div>
        );
    }
}

Apple.propTypes = {
    apple: PropTypes.object.isRequired,
    oranges: PropTypes.array.isRequired
};

【讨论】:

  • 这在很大程度上是我的想法,只是不知道如何将它硬塞到渲染器中。您的解决方案是有道理的,但是不幸的是,这样做时它不会渲染橙色对象。我会继续调查。
  • @NobodyInParticular,你的 Apple 渲染器现在是什么样子的?您必须重写它以遍历 {this.props.oranges} 并创建 Orange 渲染器。我不知道您是否尝试过,或者您认为这会自动发生。
  • 目前看起来像这样:renderApples() { return this.props.apples.map((apple) =&gt; ( &lt;Apple key={apple._id} apple={apple} oranges={Oranges.find({appleId: apple._id}).fetch()} /&gt; )); } 其次是:&lt;ul&gt; { this.renderApples() } &lt;/ul&gt; 这并不是我认为它会自动发生,我只是不知道你将如何迭代橘子。这只是一个嵌套的 for 循环,但在语法上我几乎没有成功。
  • @NobodyInParticular,我更新了我的答案以显示 Apple 组件的示例。它将获取提供给它的 oranges 属性并负责渲染橘子。
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多