首页 > 解决方案 > Chartjs 没有呈现条形图,即使在控制台记录时图表变量正确显示

问题描述

我在使用 Reactjs 使用 Chartjs 渲染条形图时遇到问题。当我 console.logged 在 componentDidMount 中创建的图表变量时,它显示了正确的标签和数据(标签:(5)[“非常积极”,“有点积极”,“中性”,“有点消极”,“非常消极”]和数据:(5) [10, 17, 35, 34, 4])。但是,当我加载页面时,条形图不显示任何数据。我没有正确渲染条形图吗?

class BarChart extends Component {
  constructor(props){
      super(props);
      this.state = {
        render: false,
        data : {
            labels: [],
            datasets: [
                {
                    label: "Number of Tweets by Sentiment Category",
                    backgroundColor: "blue",
                    data: []
                },
              ]
            }
    }
  }

  componentWillMount() {
    this.getGraphs();
  }

  componentDidMount() {
    console.log(this.state.data)
    let el = ReactDOM.findDOMNode(this.refs.chart);
    let ctx = el.getContext("2d");

    let chart = new Chart(ctx, {
        type: 'bar',
        data: this.state.data,
        options: {
            barValueSpacing: 20,
            scales: {
                yAxes: [{
                    ticks: {
                        min: 0
                    }
                }]
              }
            }
          }
        );
      console.log(chart)
      this.setState({ render: true })
      }

  getGraphs = async() => {

    let ticker = this.state.crypto;
    let name = this.state.name;

    let URL = 'http://localhost:5000/api/getGraphs';

    let response = fetch(URL, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'name': name,
        'ticker': ticker,
      }
    })
    .then((response) => response.json())
    .then((info) => {
      let data = this.state.data;

      data['labels'] = info.categories;
      data['datasets']['data'] = info.count;
      this.setState({ 'data': data })
    })
  }

  render() {
  return (
    <div className='card'>
      { this.state.render = true &&
        <canvas ref="chart" height="400px" />
      }
    </div>);

  } 
}

export default BarChart;

标签: reactjschart.js

解决方案


这条线似乎是不正确的。您在这里分配一个值,而不是检查它是否为真。

{ this.state.render = true &&
        <canvas ref="chart" height="400px" />
      }

将其更改为:

{ this.state.render &&
        <canvas ref="chart" height="400px" />
      }

这可能不是根本原因,但只是想指出它。


推荐阅读