简体   繁体   中英

React-D3 using fetch data

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

    this.state = {
      data: null
    }

    this.fetchData = this.fetchData.bind(this);
    this.barChart = this.barChart.bind(this);
  }

  componentDidMount() {
    this.fetchData();
    this.barChart(this.state.data);
  }

  fetchData() {
    const API = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json'

    fetch(API)
    .then(response => response.json())
    .then(data => {
      this.setState({
        data: data.data
      })
    })
  }

  barChart(dataset) {
    const canvasWidth = 600;
    const canvasHeight = 400;
    const svgCanvas = d3.select(this.refs.canvas)
                     .append('svg')
                     .attr('width', canvasWidth)
                     .attr('height', canvasHeight)

    const xScale = d3.scaleLinear()
                      .domain([0, d3.max(dataset, d => d[0])])
                      .range([0, canvasWidth])

    const yScale = d3.scaleLinear()
                      .domain([0, d3.max(dataset, d => d[1])])
                      .range([canvasHeight, 0])

    svgCanvas.selectAll('rect')
            .data(dataset)
            .enter()
              .append('rect')
              .attr('class', 'bar')
              .attr('x', (d, i) => i * 30)
              .attr('y', d => yScale(d[1]))
              .attr('width', xScale(25))
              .attr('height', d => yScale(d[1]))

  }

  render() {
    return (
      <d>
        <div id='title'>my chart</div>
        <div ref='canvas'></div>
      </d>
    )
  }
}

ReactDOM.render(<MyChart />, document.getElementById('app'))

I am using React to visualize the graph with D3. I tried to fetch data of GDP, and use the data, but I have got nothing on the page.

when I just put an array as an input to test by myself instead of fetching data, it shows at least something based on the input. I think the problem occurs when fetching data

Any thoughts on this matter?

When the component start rendering, first thing will be called componentDidMount() .So in your componentDidMount() two things are there

  1. fetching api
  2. rendering barchart , which will be run in same batch

So when api call happen setState will not assign state.data value as it is asynchronous. But next when your barchart want to render, it's getting null value as argument.

Thats the reason it's not working.

I suggest u to put the this.barChart(data.data) inside the fetch api.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM