javascript reactJS 并读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52373802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reactJS and reading a text file
提问by Jonathan Small
I have a reactJS application where I need to read in a large text file and use the data from the file to populate some arrays. I came across some code examples and I am trying to implement this code:
我有一个 reactJS 应用程序,我需要在其中读取一个大文本文件并使用文件中的数据填充一些数组。我遇到了一些代码示例,我正在尝试实现此代码:
readTextFile = file => {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = () => {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
console.log("allText: ", allText);
this.setState({
fundData: allText
});
}
}
};
rawFile.send(null);
};
The code is called by executing this line of code:
通过执行这行代码来调用代码:
this.readTextFile("../text/fund_list.txt");
When I execute the application, I get the following error message:
当我执行应用程序时,我收到以下错误消息:
GET http://localhost:8080/text/fund_list.txt404 (Not Found)
GET http://localhost:8080/text/fund_list.txt404(未找到)
This is what my application structure looks like:

The readTextFile function is in the account_balanc.js code and I am trying to read in the text file /text/fund_list.txt. The file does exist so obviously I am not referencing the file correctly but I don't know why.
readTextFile 函数位于 account_balanc.js 代码中,我正在尝试读取文本文件 /text/fund_list.txt。该文件确实存在,所以显然我没有正确引用该文件,但我不知道为什么。
I have tried this.readTextFile("../text/fund_list.txt") and this.readTextFile("./text/fund_list.txt"); but neither worked. I even tried moving fund_list.txt into the /screens folder and changing the function call to this.readTextFile("fund_list.txt"); but I still get the 404 error message.
我试过 this.readTextFile("../text/fund_list.txt") 和 this.readTextFile("./text/fund_list.txt"); 但都没有奏效。我什至尝试将 fund_list.txt 移动到 /screens 文件夹并将函数调用更改为 this.readTextFile("fund_list.txt"); 但我仍然收到 404 错误消息。
Any ideas why?
任何想法为什么?
Thank you.
谢谢你。
回答by Jonathan Small
I moved the fund_list.txt file into the public/text folder (after I created it) and changed the calling of the function to this.readTextFile("./text/fund_list.txt");
我将fund_list.txt 文件移动到public/text 文件夹(在我创建它之后)并将函数的调用更改为this.readTextFile("./text/fund_list.txt");
I saw this as a posted solution but then the post was removed (I don't know why) so I can't thank the user who posted it. But this solved my problem.
我将此视为已发布的解决方案,但随后该帖子已被删除(我不知道为什么)所以我无法感谢发布它的用户。但这解决了我的问题。
回答by P Fuster
I'm assuming you are using Webpack as the bundler.
我假设您使用 Webpack 作为打包器。
The reason you were getting a 404 Not Found is because you need to configure Webpack to bundle the file into the build folder the website is hosting.
您收到 404 Not Found 的原因是您需要配置 Webpack 以将文件捆绑到网站托管的构建文件夹中。
Moving it to the /publicfolder worked because Webpack was configured to bundle all the files in the /publicfolder as it is usually the entry point of the project (since this is probably create-react-app).
将它移动到/public文件夹是有效的,因为 Webpack 被配置为捆绑文件/public夹中的所有文件,因为它通常是项目的入口点(因为这可能是 create-react-app)。
Also the folks at create-react-app are smart and saw that if it was a .txtextension file, they would bundle them into a /textfolder in the build file, just as any .jpgor .pngfiles will bundle into a /imagesfolder.
create-react-app 的人也很聪明,他们看到如果它是一个.txt扩展文件,他们会将它们捆绑到/text构建文件中的一个文件夹中,就像 any.jpg或.pngfiles 将捆绑到一个/images文件夹中一样。
Note that a lot of files need a special webpack loader if you import them in project, but you can also use a webpack plugin to copy the file into your bundle and then read that programmatically as you are doing.
请注意,如果您在项目中导入它们,很多文件需要一个特殊的 webpack 加载器,但您也可以使用 webpack 插件将文件复制到您的包中,然后在您执行时以编程方式读取。
Therefore once you moved it to that folder your application could actually find it in the build folder -hosted in localhost:8080!
因此,一旦您将其移动到该文件夹,您的应用程序实际上可以在构建文件夹中找到它 - 托管在localhost:8080!
回答by Soroush Chehresa
You can use webpack raw loaderand directly import the .txtfile into the component.
你可以使用webpack raw loader直接将.txt文件导入到组件中。
First, install raw-loader:
首先,安装raw-loader:
npm i -D raw-loader
Second, add the loader to your webpack config:
其次,将加载器添加到您的 webpack 配置中:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/,
use: 'raw-loader'
}
]
}
}
Then, directly import .txtto your component:
然后,直接导入.txt到您的组件中:
import txt from './file.txt';
回答by Zeeshan Ahmad
Using HTML5 FileReaderAPI you can easily read any file. Please have look at the following code:
使用 HTML5 FileReaderAPI,您可以轻松读取任何文件。请查看以下代码:
function App() {
const [json, setJson] = useState("");
let fileInputRef = React.createRef();
return (
<div className="App">
<p>{json}</p>
<input
type="file"
ref={fileInputRef}
style={{ display: "none" }}
onChange={async e => {
const reader = new FileReader();
reader.onload = function() {
const text = reader.result;
setJson(text);
};
reader.readAsText(e.target.files[0]);
}}
accept=".json,application/json"
/>
<button
onClick={() => {
fileInputRef.current.click();
}}
>
Upload JSON file
</button>
</div>
);
}
Here is a working Demo
这是一个工作演示
回答by Derek Sweet
I don't have a lot of experience with pure javascript applications, I usually use a rails backend, but I would recommend focusing on just being able to hit http://localhost:8080/text/fund_list.txtin a browser and get a response. Once you solve that it looks like the javascript will do it's thing.
我对纯 javascript 应用程序没有很多经验,我通常使用 rails 后端,但我建议专注于能够在浏览器中点击http://localhost:8080/text/fund_list.txt并获得一个回应。一旦你解决了它看起来像 javascript 会做它的事情。
回答by AJ Genung
Try...
尝试...
const file = require("../text/fund_list.txt");
Then
然后
this.readTextFile(file);

