简体   繁体   English

我如何 map 阵列与多个对象并显示在图表上?

[英]How can I map array with multiple objects and display on chart?

I want to display my data that I collect from firestore database and show it on charts, using Rechart in React.我想显示我从 firestore 数据库收集的数据,并使用 React 中的 Rechart 将其显示在图表上。 This is how my data looks like:这就是我的数据的样子:

在此处输入图像描述

When I want to display everyting on one chart - everything works fine.当我想在一张图表上显示所有内容时 - 一切正常。 But I want to create that many single charts how much objects I have.但我想创建那么多单张图表我有多少对象。 I mean, every new trip = new chart.我的意思是,每一次新的旅行=新的图表。

This is how my code looks like right now.这就是我的代码现在的样子。

Saving data into array将数据保存到数组中


const getData = async () => {
    const data = [];

    const querySnapshot = await getDocs(
      collection(databaseRef, `${cUser}/userinfo/trips`)
    );
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data().Title);
      data.push({
        Trip: doc.data().Trip,
        Distance: doc.data().Distance,
        Time: doc.data().Time,
        Calories: doc.data().Calories,
      });
    });
    setData(data);
    console.log(data);
  };

This code generate 2 different charts, what is OK but without any data.此代码生成 2 个不同的图表,可以但没有任何数据。

 {dataToShow.map((item) => {
        return (
          <>
            <BarChart width={600} height={600} data={item}>
              <XAxis dataKey={item.Trip} />
              <YAxis dataKey={item.Distance} />

              <Bar dataKey={item.Calories} barSize={30} fill="#8884d8" />
              <Bar dataKey={item.Time} barSize={30} fill="#fcba03" />
            </BarChart>
          </>
        );
      })}

What's wrong with my mapping?我的映射有什么问题?

Thanks for any help!谢谢你的帮助!

To display your different Bar elements, you don't need to loop into every item of your array.要显示不同的Bar元素,您不需要循环到数组的每个项目。

Instead, you just need to use the prop dataKey per Bar, where you specify the data you want to use as a string, just like the following:相反,您只需要使用dataKey per Bar,在其中指定要用作字符串的数据,如下所示:

// {dataToShow.map((item) => { <-- remove this
return (
  <BarChart width={600} height={600} data={dataToShow}> // update the `data` prop with your data array
    <XAxis dataKey="Trip" />
    <YAxis dataKey="Distance" />

    <Bar dataKey="Calories" barSize={30} fill="#8884d8" />
    <Bar dataKey="Time" barSize={30} fill="#fcba03" />
  </BarChart>
);
// })} <-- to remove

Recharts will understand the data you're pointing to with the same prop name ("Trip", and so on). Recharts 将使用相同的道具名称(“Trip”等)理解您指向的数据。

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

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