有条件地创建对象

时间:2019-02-26 12:56:04

标签: javascript reactjs

我正在使用Chartjs,并试图在一个函数中创建一次图表对象。然后跳过该函数中的那段代码,这样它就只会在以后的调用中更新图表。

我不确定如何构造条件图表对象的创建。下面是我的代码方法(它不运行atm)。

class BtcOverview extends React.Component {
  constructor(props) {
    super(props);

    this.canvasRef = React.createRef();

  }


 componentDidMount () {

    this.callApi();

  } 


  callApi = () => {

    fetch(getApi())
    .then(results => results.json())
    .then(marketData => {

      //API FETCH STUFF


    const chartOptions = {
      ...{}
      ...this.props.chartOptions
    };

    const BtcChart = new Chart(this.canvasRef.current, {
      type: "LineWithLine",
      data: this.props.chartData,
      options: chartOptions
    });




    BtcChart.render(); 

    // I want to create the BtcChart and render() on the first run. But then after that only call update() on the chart object

     }) 
  }



  render() {

    return (
     <>
          <CardBody className="pt-2">
            <canvas
              height="160"
              ref={this.canvasRef}
              style={{ maxWidth: "100% !important" }} className="mb-1" />

          </CardBody>  
      </Card>
    </>

    );

  }
}

更新:我应该更清楚地解释一下。我希望能够一次创建一个“新图表”,然后在随后的运行中,而不是给定图表对象已存在,则调用BtcChart更新。

当我尝试使用if-else语句来实现它无法编译时,因为我猜是因为在编译时可能尚未创建图表BtcChart,并且可能是范围问题。因此,我一直在尝试使用可能是错误的方法的黑客程序。

0 个答案:

没有答案