简体   繁体   中英

Why does my code work when inserting it inside componentDidMount lifecycle (reactjs)?

I am trying to use chartist.js with my react component. I have downloaded the chartist.js from the link mentioned below. I have downloaded the chartist folder and saved it inside my react project.

When I insert this line -> const mychart = new Chartist.Line('.ct-chart', data);

inside componentDidMount() function I am able to see the chart on web page.

Chartist.js -> https://gionkunz.github.io/chartist-js/

Line.js:

import React, { Component } from 'react';

var data = {
  // A labels array that can contain any sort of values
  labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  // Our series array that contains series objects or in this case series data arrays
  series: [
    [5, 2, 4, 2, 0]
  ]
};

const mychart = new Chartist.Line('.ct-chart', data); <---- Line 10

class Line extends Component {

  render(){
    return(
      <div>
          <div class="ct-chart ct-perfect-fourth">
              {mychart}
          </div>
      </div>
    )}
}

export default Line;

Parent component:

render(){
   return(
     <div>
        <Line/>
     </div>
)
}

Above Line component gives error in console saying -> cannot read property querySelectorAll Now when I add Line 10 of Pie component inside componentDidMount() function my Line component works fine and it also render's component on web page but I could not understand why does it work on inserting that line 10 inside componentDidMount() function.

Below code works why but ?

componentDidMount(){
    const mychart = new Chartist.Line('.ct-chart', data);
}

Screenshot error (Note: In screenshot below Pie component is basically my Line component in above code):

在此处输入图片说明

As stated in React docs, componentDidMount() is used for those initializations that require the DOM nodes. new Chartist.Line('.ct-chart', data); clearly uses an DOM element.

As a suggestion you might try react-chartist that is a "React component for Chartist.js".

Cheers!

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