【问题标题】:Loop through Meteor React components循环通过 Meteor React 组件
【发布时间】:2016-12-04 18:21:37
【问题描述】:

在带有 React 的 Meteor 1.4 中,我想做一个渲染组件的嵌套循环,每行 2 行,每行 6 个项目。

Row 1
[unique_item] [unique_item] [unique_item] ...
Row 2
[unique_item] [unique_item] [unique_item] ...

如何将状态传递给createContainer 函数,以便我可以递增计数器以对结果进行分页?

代码如下:

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { createContainer } from 'meteor/react-meteor-data';

import { Items } from '../api/items.js';
import Item from './Item.jsx';
import '../../client/stylesheets/main.scss';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      skipCount : 0
    };
  }

  renderItemRows(i) {
    return  ( 
      <div className="container-fluid">
          <div className="row">
             { this.renderItems(i) }
          </div>
        </div>   
      );
  }


  renderItems(i) {
   // i here has the right value...how do I pass into createContainer?
   return this.props.items.map((item) => (
      <Item key={item._id} item={item} />
    ));
  }

  render() {
    let rows = []; 
    for (let i=0;i<2;i++) {
      rows.push(this.renderItemRows(i));
    }
    return (<div>{rows}</div>);
  }
}


App.propTypes = {
  items: PropTypes.array.isRequired,
  skipCount: PropTypes.number,
};

export default createContainer(() => {
  // Hardcoded to 50 just to make sure the data pagination works
  const skipCount  = 50;
  Meteor.subscribe('items', skipCount);
  return {
    items: Items.find({}, { sort: { item : 1 }, limit : 6 }).fetch(),
  };
}, App);

在阅读 Meteor 论坛上的 this thread 之后,createContainer() 被作为无状态函数传递,因此无法将这样的信息传递给它。

根据那个帖子,我只有两个选择:

  1. 创建包装组件(ItemRow1.jsxItemRow2.jsx
  2. 通过Session.get()将参数传递给发布函数

我尝试了 2 号,但它开始每秒读取 Session.get 数百次,导致我的应用程序停止。

没有。 1 会起作用,但似乎只是为了通过第二行数据分页而令人难以置信的重复......有没有更好的方法来做到这一点?

【问题讨论】:

  • 我不确定我是否理解您想要实现的目标。您的问题是否与您的 i 变量或 skipCount 相关(在您的代码中,您可能对两者都有问题)?您是要动态呈现可变数量的行,还是一次总是这 2 行?
  • 我希望始终呈现 2 行,每行 6 个项目。 skipCount 只是对结果进行分页,所以第 1 行是 1-6,第 2 行是 7-12。

标签: reactjs meteor


【解决方案1】:

如果我正确理解您要执行的操作,最简单的方法是为createContainer 中的第 1 行和第 2 行创建单独的项目数组:

return {
  items1: Items.find({}, { sort: { item : 1 }, limit : 6 }).fetch(),
  items2: Items.find({}, { sort: { item : 1 }, skip: 6, limit : 6 }).fetch(),
};

你当然也需要修改propTypes

items1: PropTypes.array.isRequired,
items2: PropTypes.array.isRequired,

现在在renderItems 方法中,您可以这样做:

return this.props[`items${i+1}`].map((item) => (
  <Item key={item._id} item={item} />
));

或者,由于您只有两行(显然不需要支持任何其他行数),您可以从数据库中获取 12 个项目,然后将它们呈现在 renderItemsslice 中,就像这样:

const items = (i === 0) ? this.props.items.slice(0, 7) : this.props.items.slice(7);
return items.map((item) => (
  <Item key={item._id} item={item} />
));

这取决于你的实际代码哪种方式更干净,所以随你喜欢。

【讨论】:

  • 正是我需要的。惊人的答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多