[英]How to import a CSV file in ReactJs?
I am trying to import a csv file that is in a folder called data on the same level as this function. I've tried to incorporate the solution I found on here, but no luck and I don't know what I need to modify.我正在尝试导入一个 csv 文件,该文件位于与此 function 处于同一级别的名为数据的文件夹中。我尝试合并我在此处找到的解决方案,但没有运气,我不知道我需要修改什么.
getData.jsx获取数据.jsx
import React, { useState, useEffect } from 'react';
import Papa from 'papaparse';
export default function GetData(artist) {
const data = Papa.parse(fetchCsv);
console.log(data);
return data;
}
async function fetchCsv() {
const response = await fetch('data/artist_data.csv');
const reader = response.body.getReader();
const result = await reader.read();
const decoder = new TextDecoder('utf-8');
const csv = decoder.decode(result.value);
return csv;
}
Few problems I see here.我在这里看到的问题很少。
fetch('data/mycsv.csv')
you are essentially making a request to http://localhost:3000/data/mycsv.csv
.fetch('data/mycsv.csv')
时,您实际上是在向http://localhost:3000/data/mycsv.csv
。 Check the n/w tab and you will see the response returned is your html
.html
。 React first loads your root page and then checks further for routes. fetchCsv
fun inside GetData
function. Also you need to await for fetchCsv
.GetData
function 中调用fetchCsv
函数。您还需要等待fetchCsv
。 Solution:解决方案:
Move your data
folder which has your csv file to the public folder and make corrections to your code.将包含 csv 文件的
data
文件夹移动到公共文件夹并更正您的代码。
import React from 'react';
import Papa from 'papaparse';
async function GetData(artist) {
const data = Papa.parse(await fetchCsv());
console.log(data);
return data;
}
async function fetchCsv() {
const response = await fetch('data/mycsv.csv');
const reader = response.body.getReader();
const result = await reader.read();
const decoder = new TextDecoder('utf-8');
const csv = await decoder.decode(result.value);
console.log('csv', csv);
return csv;
}
I have tested the above code in my local and it works fine.我已经在我的本地测试了上面的代码并且它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.