简体   繁体   English

根据数组数据创建React组件

[英]Creating react components from array data

I am creating a fairly simple stats page for a dashboard in my rails application. 我正在Rails应用程序中为仪表板创建一个非常简单的统计信息页面。 I am using react-rails to create react components in my app and have one for a stat card. 我正在使用react-rails在我的应用程序中创建react组件,并且有一个用于stat卡的组件。 在此处输入图片说明

For these cards I have created a very simple react component 对于这些卡,我创建了一个非常简单的react组件

import React from "react";
import PropTypes from "prop-types";
class StatCard extends React.Component {
  render() {
    const { title, data } = this.props;
    return (
      <React.Fragment>
        <div className="card">
          <div className="card-body">
            <div className="row align-items-center">
              <div className="col">
                <h6 className="card-title text-uppercase text-muted mb-2">
                  {title}
                </h6>

                <span className="h2 mb-0">{data}</span>
              </div>
              <div className="col-auto">
                <span className="h2 fe fe-briefcase text-muted mb-0" />
              </div>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

StatCard.propTypes = {
  title: PropTypes.string,
  data: PropTypes.integer
};
export default StatCard;

In my html page right now I have 4 different components listed by calling this 4 different types with different data and a different title. 现在在我的html页面中,通过调用具有不同数据和不同标题的这4种不同类型,列出了4种不同的组件。

<%= react_component("StatCard", {title: 'Total users', data: @users.count }) %>

Would the best practice be to list an array of objects with this data listed and iterate over that and generate those components that way? 最佳实践是列出列出了此数据的对象数组并对其进行迭代并以这种方式生成那些组件吗? If so, would this be data be best in the model or the controller? 如果是这样,这是否是模型或控制器中最好的数据?

The data structure might look something like this. 数据结构可能看起来像这样。

data = [
  { title: 'Total users', data: @users.count },
  { title: 'Total questions', data: @questions.count }
]

It is a good practice to have array of objects and iterate through that to return multiple similar components. 拥有对象数组并进行迭代以返回多个相似的组件是一个好习惯。 you are using instance of user to get the count so it would be fine if you have them in controller 您正在使用用户实例获取计数,所以如果您将它们放在控制器中会很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM