React Chart.js BarGraph不更新

问题描述

我正在尝试使用 Out [2]: ID Invoice_Date Payment_Term Payment_Date Due_Date Delay diff days Mean 0 27459 2020-06-26 7 2020-07-05 2020-07-03 2 0.0 0.0 1 27459 2020-06-29 8 2020-07-05 2020-07-07 -2 3.0 3.0 2 27459 2020-06-30 3 2020-07-03 2020-07-03 0 1.0 4.0 3 27459 2020-07-14 6 2020-07-21 2020-07-20 1 14.0 18.0 4 27459 2020-07-25 4 2020-07-31 2020-07-29 2 11.0 29.0 0.6 5 27459 2020-07-30 7 2020-08-15 2020-08-06 9 5.0 5.0 6 27459 2020-08-02 8 2020-08-22 2020-08-10 12 3.0 8.0 10.5 7 48002 2020-05-13 5 2020-06-16 2020-05-18 29 0.0 0.0 29 8 48002 2020-06-20 3 2020-06-23 2020-06-23 0 38.0 0.0 9 48002 2020-06-28 6 2020-07-05 2020-07-04 1 8.0 8.0 0.5 实现条形图,但是在向其传递数据时遇到一些问题。

如果我在调用图形时直接声明了数组,那么它将起作用:

react-chartjs-2

first way

但是如果我尝试类似的操作:

render(){
      return(
        <div>
          <NumberField label={"n"} min={0} max={9999999} handleChange={this.changeN}/>
          <NumberField label={"p"} min={0} max={1} handleChange={this.changeP}/>
          <distribution name={this.state.name} 
            media={this.state.media} 
            varianza={this.state.varianza}
            desviacion={this.state.desviacion}
          />
          <Bargraph _labels={['a','b']} _data= {[1,2]}/>
          
        </div>
      )
    }

图形无法正确呈现:second way

这是Bargraph组件:

constructor (props) {
      super(props);
      this.changeN = this.changeN.bind(this);
      this.changeP = this.changeP.bind(this);

      this.state={
        name: "Binomial",p: 0,n: 0,media: 0,varianza: 0,desviacion: 0,labels: [],data: []
      }
    }

    componentDidUpdate(_prevProps,prevstate) {
      if (prevstate.p !== this.state.p || prevstate.n !== this.state.n) {
        
        this.setState({
          media: this.calcularMedia(),varianza: this.calcularVarianza(),desviacion: this.calcularDesviacion(),data: [1,2],labels: ['a','b']
        });
      }
    }

·········

render(){
      return(
        <div>
          <NumberField label={"n"} min={0} max={9999999} handleChange={this.changeN}/>
          <NumberField label={"p"} min={0} max={1} handleChange={this.changeP}/>
          <distribution name={this.state.name} 
            media={this.state.media} 
            varianza={this.state.varianza}
            desviacion={this.state.desviacion}
          />
          <Bargraph _labels={this.state.labels} _data= {this.state.data}/>
          
        </div>
      )
    }

谢谢。

解决方法

在主文件中声明数据并传递它可以正常工作:

const graphData= {
  labels: ['t1','t2'],datasets: [
    {
      backgroundColor: 'rgba(90,172,170,0.8)',data: [15,78]
    }
  ]
}

class Binomial extends Component {
render(){
      console.log(this.state.data);
      console.log(this.state.labels);
      return(
        <div>
          <BarGraph3 data={graphData}/>
        </div>
      )
    }
}
}