图表:在BarChart中循环两次时不显示

时间:2019-04-12 11:29:16

标签: reactjs recharts

我使用图表显示图表。
我的数据如下:

const data = [
      {name: 'day 1', supermarket1:{strawberry:4090, apple:3740} , supermarket2:{strawberry:6498, apple:1008}, supermarket3:{strawberry:4090, apple:3740}},
      {name: 'day 2', supermarket1:{strawberry:200, apple:768} , supermarket2:{strawberry:700, apple:876}, supermarket3:{strawberry:300, apple:932}}
]

我想在条形图内循环两次以显示我的数据

我尝试在条形图内仅进行一次循环,但效果很好,但是当我要循环两次时,显示屏没有出现,我也不知道为什么

我的代码如下:

const SimpleBarChart = React.createClass({
    render () {
    return (
        <BarChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <CartesianGrid strokeDasharray="3 3"/>
       <XAxis dataKey="name"/>
       <YAxis/>
       {["supermarket1", "supermarket2", "supermarket3"].map((elt, index) =>{
         ["strawberry", "apple"].map((fruit, index2) =>{
         console.log(`${elt}.${fruit}`);
         return(
           <Bar
             key={index + index2}
             dataKey={`${elt}.${fruit}`}
             fill="#1f77b4"
           >
           </Bar>
         )
         })
       })}
      </BarChart>
    );
  }
})

1 个答案:

答案 0 :(得分:0)

解决方案是在BarChart外部映射两次,并按需要在第三个数组中组织数据以在BarChart内部使用。

const SimpleBarChart = React.createClass({
    render () {
  let keys= [];
  {["supermarket1", "supermarket2", "supermarket3"].map((elt, index) =>{
       ["strawberry", "apple"].map((fruit, index2) =>{
       keys.push(`${elt}.${fruit}`)
       })
       })}  
    return (
        <BarChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <CartesianGrid strokeDasharray="3 3"/>
       <XAxis dataKey="name"/>
       <YAxis/>

       {keys.map((key, index) =>{

       return(
       <Bar
         key={index}
         dataKey={`${key}`}
         fill="#1f77b4"
       ></Bar>
       )
       })}
      </BarChart>
    );
  }
})

demo