简体   繁体   English

如何在ReactJs中导入一个CSV的文件?

[英]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.我在这里看到的问题很少。

  1. When you do 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 .检查 n/w 选项卡,您将看到返回的响应是您的html React first loads your root page and then checks further for routes. React 首先加载您的根页面,然后进一步检查路由。
  2. Some coding errors like - you haven't called the 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.

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