首页 > 解决方案 > CSV not returning rows

问题描述

been stuck on this all morning. I've been following this example

I've been trying to get this to work in React but sadly no luck. I was able to read the csv in before and console log the data so I know it's finding the right file. What am I missing here?

class Linegraph extends Component {
    componentDidMount() {
    var parseDate = d3.timeParse("%m/%d/%Y");

    var margin = { left: 50, right: 20, top: 20, bottom: 50 };

    var width = 960 - margin.left - margin.right;
    var height = 500 - margin.top - margin.bottom;

    var max = 0;

    var xNudge = 50;
    var yNudge = 20;

    var minDate = new Date();
    var maxDate = new Date();

    d3.csv("MOCK_DATA.csv")
      .row(function(d) {
        return {
          month: parseDate(d.month),
          price: Number(d.price.trim().slice(1))
        };
      })
      .get(function(error, rows) {
        max = d3.max(rows, function(d) {
          return d.price;
        });
        minDate = d3.min(rows, function(d) {
          return d.month;
        });
        maxDate = d3.max(rows, function(d) {
          return d.month;
        });
    .................

标签: javascriptreactjsd3.js

解决方案


(note: this question is not a duplicate of the existing Q/A about the new d3.fetch module because it uses a row function, not covered on those Q/A)

Since you are using D3 v5, you have to change the XmlHttpRequest pattern of v4 to the new Promises pattern of v5 (see the documentation here).

So, your code should be:

d3.csv("MOCK_DATA.csv", function(d) {
        return {
            month: parseDate(d.month),
            price: Number(d.price.trim().slice(1))
        };
    })
    .then(function(rows) {
    //etc...
    });

Pay attention to the fact that the row function goes inside the d3.csv function, as the second argument.


推荐阅读