使用图表无法在React js中显示条形图

时间:2019-04-23 07:45:18

标签: reactjs recharts

我正在尝试使用React js中的图表构建条形图。 我正在使用fetch调用从API提取数据并将其转换为数组。但是当显示barCharts时,它将变为空白。

任何人都可以帮助我哪里出问题了

var data1=[];



class BarChart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: new Date(),
      endDate: new Date(),
      count: false,
      formsubmit: false,
      formsubmit1: false,
      modalShow: false,
      items: [],
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    });
  }
   handleClick1 = e => {
    e.preventDefault();
     var URL =
       " http://localhost:8080/fetchdata;
    this.setState({ formsubmit: true });
    console.log(URL);
    fetch(URL, {
    method: "GET",
     })
     .then(res => res.json()).then(data=>
       {
     console.log("Response Success!!")
    this.setState({items:data});
    data1=this.state.items;
    console.log(this.state.items);
    }) 
  };  

  render() {

    return (
      <div style={{ marginTop: 40 }}>


              <Button
                onClick={this.handleClick1}
                style={{
                  background:
                    "linear-gradient(to left bottom,rgb(31, 130, 167), rgb(161,215,232))",
                  fontSize: "small",
                  marginLeft: "20%"
                }}
              >
                VIEW METRICS
              </Button>
          </div>
               <div>
            {this.state.formsubmit && (
              <BarChart width={500} height={300} data={data1}>
                <XAxis dataKey="Total" />
                <YAxis />
                <Tooltip cursor={false} />
                <Legend />
                <Bar dataKey="Success" stackId="a" fill="#8884d8" label />
                <Bar
                  dataKey="Failure"
                  onClick={this.handleClick}
                  stackId="a"
                  fill="#82ca9d"
                  label
                />
              </BarChart>
            )}
          </div>

    );
  }
}
export default withStyles(styles)(BarChart);`

我已经检查了控制台日志。它正在以阵列形式显示数据。enter image description here

有人可以建议我要去哪里吗?

2 个答案:

答案 0 :(得分:0)

date email points 04_21_2018 abc@gmail.com 200 04_15_2020 abc1@gmail.com 300 01_2_2019 abc2@gmail.com 800 data1最初为空,并且未处于状态。因此,当您用数据填充时,React无法理解它是否已更改,因此不会发生任何<BarChart width={500} height={300} data={data1}>的重新渲染,如果没有使函数异步并使用await的话

答案 1 :(得分:0)

您正在将数据obj定义为变量,您需要访问状态,以便在更改状态时,组件将重新呈现。 除了一个异步请求,您的第一个数据初始化为空,因此条形图变得不确定。

更改为:

data={this.state.items}