首页 > 解决方案 > 尝试使用图表中的数据显示表格

问题描述

我正在尝试根据所选内容(选择哪个栏)呈现具有两列的表格。每个条是一个日期数组。

因此,如果单击最后一个栏,我想要一个月份表,其中包含该月在该数组中出现的次数。

例如,在最后一个栏中,这是显示在控制台中的数组,该数组由第 62 行中的函数创建:

0: {date: 5, count: 1}
1: {date: 7, count: 15}
2: {date: 7, count: 15}
3: {date: 7, count: 15}
4: {date: 7, count: 15}
5: {date: 7, count: 15}     

ETC..

功能:

const table = (data, e ) =>{
    // get array of dates when bar is clicked 
    let newArr= data.datum.dimensions[0].datum.data.results.map((d) => d.Date)
    console.log(newArr)

    // convert into Date object 
    const datesArr = newArr.map(d => ({ date: new Date(d) , count : 0}))
    console.log(datesArr)


    // add month array with month as an integer and the the count of months (how many times each month shows up )
    const monthArr = datesArr.map((e) => ({date: e.date.getMonth(), count: 0}))
    monthArr.forEach((e) => e.count = datesArr.filter((d) => d.date.getMonth() === e.date).length)
    console.log(monthArr)
    setMonths(monthArr)
}

我正在使用状态,我只是想使用带有这个数组和计数的 JSX 来呈现一个表

所以我想要一张表,其中一列中有月份,另一列中有计数 - 像这样:

<tr>
      <th>Year
      <select name="format" id="format"
        onChange={(e) => {
             table()
        }}
      >
          <option value='months'>months</option>
  
      </select>
      </th>
      <th>
        count
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{months}</td>
      <td> // count goes here </td>
    </tr>
    
  </tbody>
</Table> */}

这是完整沙箱的链接:https ://codesandbox.io/s/nice-meitner-o70m1

标签: javascriptreactjsnivo-react

解决方案


您的逻辑有点混乱table(),我刚刚重写了它必须易于理解。

除此之外,您只需要一张您所在months州的地图,如下所示:

    <Table striped bordered hover size="sm">
      <thead>
        <tr>
          <th>
            Month
            <select name="format" id="format" onChange={console.log}>
              <option value="months">months</option>
              <option value="year">year</option>
            </select>
          </th>
          <th>count</th>
        </tr>
      </thead>
      <tbody>
        {months.map(({ date, count }, index) => (
          <tr key={index}>
            <td>{date}</td>
            <td>{count}</td>
          </tr>
        ))}
      </tbody>
    </Table>

看看我的更改,看看它是否更干净,否则您必须过滤monthArr之前的地图,因为它有重复的值。

https://codesandbox.io/s/summer-lake-g0wki?file=/src/chart.js


推荐阅读