首页 > 解决方案 > 在 react.js 中填充必要的数据

问题描述

class TodoApp extends React.Component {
   constructor(){
    super();
    this.state = {

    }
  }

  componentWillMount(){
    this.getSampleData();
  }

  getSampleData(){ 
   console.log('enter value');
    this.setState({
      sampleData:{
        labels: ['Jan', 'Feb', 'Mar', 'Apr',
                  'May', 'Jun', 'Jul', 'Aug',
                   'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [
            {
                label: '2017',
                data: [92, 50, 33, 70, 122, 22, 21,20, 22, 215, 278, 190],

            },
            {
              label: '2018',
              data: [22, 210, 520, 278, 260, 245, 221,516, 718, 174, 154, 148],

          },
        ]
    }} );
    /// Here i want to get monthdata that to be taken from sampleData
monthData:
   //for example this month 221 should come here,from the sampleData
    console.log('end value');


  }

  render() {
    return (
      <div>
        <h2>Todos:</h2>
       <p> monthData</p>
      </div>
    )
  }
}

我是 React.js 的新手。但是在标签中显示时我无法放置特定月份的数据。虽然我在这里提到了monthData这个词,但我对变量引用(sampleData)和从html中获取数据没有适当的了解。在不使用 monthData 变量的情况下,直接从 sampleData 在 p 标签中制作特定月份值对我来说也很好。谁可以帮我这个事。谢谢。

标签: javascriptarraysreactjs

解决方案


在这里,我得到了基于当前月份的数据。同样,如果您想要动态的,您可以将其更改为年份。请检查下面的更新片段:

class TodoApp extends React.Component {
   constructor(){
    super();
    this.state = {

    }
  }

  componentWillMount(){
    this.getSampleData();
  }

  getSampleData(){
   console.log('enter value');
    this.setState({
      sampleData:{
        labels: ['Jan', 'Feb', 'Mar', 'Apr',
              'May', 'Jun', 'Jul', 'Aug',
               'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [
        {
            label: '2017',
            data: [92, 50, 33, 70, 122, 22, 21,20, 22, 215, 278, 190],

        },
        {
          label: '2018',
          data: [22, 210, 520, 278, 260, 245, 221,516, 718, 174, 154, 148],

        },
      ]
    }} );
    /// Here i want to get monthdata that to be taken from sampleData
    monthData:
   //for example this month 221 should come here,from the sampleData
   console.log('end value');


  }

  render() {
    const d = new Date();
    const m = d.getMonth();
    const monthData = this.state.sampleData.datasets[1].data[m];
    return (
      <div>
        <h2>Todos:</h2>
        <p>Current Month data : {monthData}</p>
      </div>
    )
  }
}

这里data[m]代表当前月份(6 - 七月)。


推荐阅读