簡體   English   中英

reactjs 中的 Plot 條形圖

[英]Plot bar graph in reactjs

我正在學習 reactjs 並且我正在嘗試 plot 條形圖。 所以我試圖 plot 人口種族圖隨着時間的推移而變化,看起來像這樣。 人口種族條形圖

為了繪制圖表,我使用的是chart-race-react 但似乎我在我的代碼中做錯了什么。

我的代碼:

import React, { Component } from 'react';
import BarChart from 'chart-race-react';

import './App.css';
const API_URL = 'https://example.json';

const randomColor = () => {
  return `rgb(${255 * Math.random()}, ${255 * Math.random()}, ${255})`;
}

class App extends Component {
 constructor(props) {
     super(props);
     this.state = {
     countries: []
   }
 }

componentDidMount() {

fetch(API_URL)
.then(v => v.json())
.then(array => {
  const dataForVisualisation = {};

  array.forEach(element => {
      const countryName = element['Country Name'];
      if (!dataForVisualisation[countryName]) {
         dataForVisualisation[countryName] = [];
      }
      dataForVisualisation[countryName].push(element.Value);
  });

  this.setState({countries: dataForVisualisation});
})

}

render() {

 return (
    <div style={{width: "500px"}}>

     <BarChart 
      start={true}
      data = {this.state.countries}
      len = {this.state.countries[Object.keys(this.state.countries)[0]].length}
      keys = {Object.keys(this.state.countries)}
      timeout={400}
      delay={100}
      colors = {Object.keys(this.state.countries).reduce((res, item) => ({ 
        ...res, 
        ...{ [item]: randomColor() } 
    }), {})}
      labels = {Object.keys(this.state.countries).reduce((res, item, idx) => {
        return{
        ...res, 
        ...{[item]: (
          <div style={{textAlign:"center",}}>
            <div>{item}</div>
          </div>
          )}
      }}, {})}
      timeline = {Array(20).fill(0).map((itm, idx) => idx + 1)}
      timelineStyle={{
        textAlign: "center",
        fontSize: "50px",
        color: "rgb(148, 148, 148)",
        marginBottom: "100px"
      }}
      textBoxStyle={{
        textAlign: "right",
        color: "rgb(133, 131, 131)",
        fontSize: "30px",
      }}
      barStyle={{
        height: "60px",
        marginTop: "10px",
        borderRadius: "10px",
      }}
      width={[15, 75, 10]}

      maxItems = {this.state.countries.length}

    />

  </div>
    );
  }
}
export default App;

我遇到TypeError: this.state.countries[Object.keys(...)[0]] is undefined錯誤,因為我的數據在這里未定義。 我應該如何更改我的代碼以使我的 output 如gif所示? 有沒有其他圖書館可以做到這一點?

我在您的代碼中發現了一個問題,例如在BarChartlen屬性中,它得到錯誤Cannot read property 'length' of undefined 在我使用帶有問號的 null 檢查后,我沒有收到任何錯誤,而是打印 1 到 20。我不確定它是否對您有幫助。 可能是在改變它之后,你會得到它的解決。

len={this.state.countries[Object.keys(this.state.countries)[0]].length}

取而代之

len={this.state.countries[Object.keys(this.state.countries)[0]]?.length}

在嘗試渲染任何內容之前,您應該等到國家/地區被填滿。 例如,僅當國家數組具有至少一個元素時,您才能呈現 BarChart 組件:

[...]
{this.state.countries.length > 0 && <BarChart 
  start={true}
  data = {this.state.countries}
  len = {this.state.countries[Object.keys(this.state.countries)[0]].length}
  keys = {Object.keys(this.state.countries)}
  timeout={400}
  delay={100}
  colors = {Object.keys(this.state.countries).reduce((res, item) => ({ 
    ...res, 
    ...{ [item]: randomColor() } 
}), {})}
  labels = {Object.keys(this.state.countries).reduce((res, item, idx) => {
    return{
    ...res, 
    ...{[item]: (
      <div style={{textAlign:"center",}}>
        <div>{item}</div>
      </div>
      )}
  }}, {})}
  timeline = {Array(20).fill(0).map((itm, idx) => idx + 1)}
  timelineStyle={{
    textAlign: "center",
    fontSize: "50px",
    color: "rgb(148, 148, 148)",
    marginBottom: "100px"
  }}
  textBoxStyle={{
    textAlign: "right",
    color: "rgb(133, 131, 131)",
    fontSize: "30px",
  }}
  barStyle={{
    height: "60px",
    marginTop: "10px",
    borderRadius: "10px",
  }}
  width={[15, 75, 10]}

  maxItems = {this.state.countries.length}

/>}

{this.state.countries.length === 0 && <span>Loading...</span>}
[...]

注意條件渲染語法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM