简体   繁体   中英

d3.csv returns index.html content in console.log

I am using d3 v5 with reactJS. I am calling d3.csv inside react 'List' class like following:

import React from 'react';
import * as d3 from 'd3';

class List extends React.Component{

componentDidMount(){
d3.csv("./data/data.csv").then(function(d, error){
    console.log(d);
});
}

render(){
        return(
        <div> </div>
        );
    }
} 
  export default List;

and List is being imported in following 'App' class

import React, { Component } from 'react';
import logo from './logo.svg';
import List from './components/list/List';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>          
        <List/> 
      </div>      
    );
  }
}
 export default App;

Following is the 'index.js' code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

'root' is a div id in index.html. By calling console.log in List file inside d3.csv I am getting content of index.html file in the console. But I want CSV content.

在此处输入图像描述

You could try using the import statement to load the CSV file at first. :)

import React from 'react';
import * as d3 from 'd3';
import data from "./data/data.csv";

class List extends React.Component{
  componentDidMount(){
    d3.csv(data).then(function(d, error){
      if (error) {
        console.log(error);
      } else {
        console.log(d);
      };
    });
  }

  render(){
    return(
      <div> </div>
    );
  }
} 

export default List;

I had the same issue and here's how I solved it. Check if the data is in the same directory as the index.html file. In my case, my index.html file is in the public/ folder, so I created public/data/data.csv . You can then try d3.csv('./data/data', function(data){...}) to read in the data.

If you are using hooks and useState, ensure that the URL is a string and not resolved as an object before using the data.

Before Input

Before Output

After Input

After Output

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