简体   繁体   中英

I am getting TypeError saying forEach is not a function?

I am trying to display Linechart using chartist.js. I have used reduce() to extract data from props . I have keys as year and values as average value in averages object. But I am not able to display the line chart as I am not able to see any lines on chart I am getting type error. I have created React component and inside componentDidMount() I have added my line chart code. I think the issue is related to javascript/reactjs and not chartist.js

Code:

class Linechart extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount(){

        const totals = this.props.bowldata.reduce((a, {season, econ})  => {

          if (!a[season]) {
            a[season] = {sum: 0, count: 0};
          }

          if(econ !== null){
            a[season].count++;
            a[season].sum += parseInt(econ);

          }

          return a; 

      }, {});

        const averages = {};

        Object.keys(totals).forEach(key => {   

          averages[key] = totals[key].sum / totals[key].count;

        });

      console.log(averages);

      const series = Object.values(averages);

      const labels = Object.keys(averages);

        const data = {
            series:series,
            labels:labels
        }

        this.linechart = new Chartist.Line('.ct-line-chart', data, options);
  }

  render(){
    return(
      <div>
          <div className="col-md-3 col-xs-6 ct-line-chart">
              {this.linechart}
          </div>
        </div>
    )}
}

export default Linechart ;

Using .forEach() I am trying to create new array of objects with sum/count as a value and key as year .

Screenshot: 在此处输入图片说明

在此处输入图片说明

Change your code like this see if the problem is gone. In docs it shows series should be a multidimensional array.

 const data = {
     series:[series],
     labels:labels
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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