简体   繁体   English

在反应中,如何将对象存储在数组中并以1迭代数组索引?

[英]In react, how to store object in array and iterate the array index by 1?

I have a page that displays multiple boxes and each box belongs to a specific company. 我有一个页面,其中显示多个框,每个框都属于一个特定的公司。 Each company has multiple projects and each project has multiple releases. 每个公司都有多个项目,每个项目都有多个版本。

Box 1: Company Name / Project Name / Release Name 方框1:公司名称/项目名称/发行名称

Box 2: Company Name / Project Name / Release Name 方框2:公司名称/项目名称/发行名称

I have a state defined as such: 我有这样定义的状态:

this.state = {
  companies: [],
  projects: [],
  releases: [],
  activeProjects: []
}

And here, I am fetching all the data from the database: 在这里,我正在从数据库中获取所有数据:

componentWillMount() {
  getCompanys().then(companies => {
    const projectPromises = companies.map((company) => {
      getProjects(company).then(projects => {
        const releasePromises = projects.map((project) => {
          return getReleases(project).then(releases => {
            if(projects.length > 0 || releases > 0) {
              this.setState({
                companies: companies,
                projects: projects,
                releases: releases
              });
            }
          })
        })
      })
    });
  })
}

which comes back with the following data: 并返回以下数据:

Companys:  (2) [{…}, {…}]0: {_id: {…}, company_name: "IBM", …}
Projects:  [{…}]0: {_id: {…}, project_name: "Project 101", …}
Releases:  (3) [{…}, {…}, {…}]0: {_id: {…}, release_name: "Release 103", …}

I am getting 2 companies, 1 project, and 3 releases. 我得到2家公司,1个项目和3个版本。

If I wanted to store each of my company, project, and release into my activeProjects array, how would I achieve the following? 如果我想将公司,项目和版本中的每一个存储到我的activeProjects数组中,我将如何实现以下目标?

activeProjects: [
  {
    company: ,
    project: ,
    release: 
  },
  {
    company: ,
    project: ,
    release: 
  },
]

Can someone please help me out? 有人可以帮我吗?

I want my end result to be someting like this: 我希望我的最终结果像这样:

activeProjects.map((project, index) => {
  return(
    **Box 1**
    IBM / Project 101 / Release Name goes here

    **Box 2**
    Facebook / Project 102 / Release Name goes here
  )
});

I would recommend structuring your data in the desired format from the beginning. 我建议从一开始就以所需的格式构建数据。 What I mean by this is rather than splitting your companies, projects, and releases into separate arrays in your state, just keep them nested from the start. 我的意思是,不是将您的公司,项目和发行版在您所在的州分为单独的阵列,而是从一开始就保持嵌套。

(Also from what I can tell from your code, you are overwriting the projects and releases each time so you are only left with projects for the last company and releases for the last project.) (从我的代码中可以看出,每次都覆盖项目和发布,因此只剩下最后一个公司的项目和最后一个项目的发布。)

1. First structure state like this: 1.第一个结构状态如下:

state = {
    companies: [],
    activeProjects: []
}

2. Then rework your componentWillMount method to be something like this (also I would recommend using async / await instead of callbacks for ease of readability). 2.然后将您的componentWillMount方法重做为类似这样的东西(为了便于阅读,我也建议您使用async / await而不是回调)。

async componentWillMount() {
    const companies = await getCompanies();
    for (const company of companies) {
        company.projects = await getProjects(company);
        for (const project of company.projects) {
            project.releases = await getP
        }
    }

    this.setState({ companies });
}

Here is a version that is a bit more complicated but more efficient because it can work on multiple companies/projects asynchronously rather than waiting for responses for each call before moving on: 这是一个稍微复杂但效率更高的版本,因为它可以异步地在多个公司/项目上工作,而不是在继续进行之前等待每个调用的响应:

async componentWillMount() {
    const companies = await getCompanies();
    const nestedCompanies = await Promise.all(companies.map(async company => {
        const projects = await getProjects(company);
        const nestedProjects = await Promise.all(projects.map(async project => {
            const releases = await getReleases(project);
            return {
                ...project,
                releases
            }
        }));
        return {
            ...company,
            projects: nestedProjects
        }
    }));

    this.setState({ companies: nestedCompanies });
}

Now your state will look like this: 现在,您的状态将如下所示:

{
    companies: [
        {
            id: 1,
            name: 'IBM',
            projects: [
                {
                    id: 1,
                    name: 'Project 101',
                    releases: [
                        {
                            name: 'Release Name'
                        },
                        // and so on
                    ]
                },
                // and so on
            ]
        },
        // and so on
    ]
}

3. Now looping through the data in companies should be fairly simple. 3.现在,遍历公司中的数据应该非常简单。 You can do something like this: 您可以执行以下操作:

const activeProjects = this.state.companies.map(company => {
    return company.projects.map(project => {
        return project.releases.map(release => {
            return `${company.name} / ${project.name} / ${release.name}`;
        });
    }).reduce((acc, e) => acc.concat(e), []);
}).reduce((acc, e) => acc.concat(e), []);

The above code will result in activeProjects being an array of strings, each of which have the format 'IBM / Project 101 / Release Name' . 上面的代码将导致activeProjects是一个字符串数组,每个字符串的格式为'IBM / Project 101 / Release Name' For this last step you could instead return some component like: 对于最后一步,您可以改为返回一些组件,例如:

<Box company={ company.name } project={ project.name } release={ release.name }/>,

depending on how your project is structured. 取决于项目的结构。

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

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