[英]importing and exporting es6 classes
I want to create ES6 class that reads data from a file and simply returns the content of the file, so I created a class called FileReader
which has a constructor filePath
and has a method called getFileContent
我想创建从文件中读取数据并仅返回文件内容的ES6类,因此我创建了一个名为
FileReader
的类,该类具有构造函数filePath
和一个名为getFileContent
的方法。
import fs from 'fs';
import path from 'path';
export class FileReader {
constructor(filePath) {
this.filePath = filePath;
fs.readFile(filePath, (err, data) => {
if (err) {
console.log(err);
}
this.fileContent = data;
});
}
getFileContent(separator, columns) {
console.log(this.fileContent);
}
}
I have a react component called OrderList
I want to use FileReader
inside componentDidMount
method to read the content of the file 我有一个名为
OrderList
组件,我想在componentDidMount
方法内使用FileReader
来读取文件的内容
import React from 'react';
import {FileReader} from '../Utils/FileReader';
class OrdersList extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
FileReader reader = new FileReader('');
reader.getFileContent(',' , []);
}
render() {
}
}
export default OrdersList;
the problem that I'm getting an error Unexpected token reader
so what's wrong with this approach ? 我遇到错误的问题
Unexpected token reader
那么这种方法有什么问题呢?
change this line: FileReader reader = new FileReader('');
更改此行:
FileReader reader = new FileReader('');
to const reader = new FileReader('');
到
const reader = new FileReader('');
There are two problems in your code: 您的代码中有两个问题:
fileContent
will be undefined, because fs.readFile
is async function. fs.readFile
是异步函数,因此fileContent
将是未定义的。 FileReader reader = new FileReader('');
FileReader reader = new FileReader('');
To fix described problems you should move the logic for reading file in class function and use callback or promise: 要解决所描述的问题,您应该在类函数中移动读取文件的逻辑,并使用回调或Promise:
class OrdersList extends React.Component {
constructor(filePath) {
this.filePath = filePath;
}
getFileContent(separator, columns, cb) {
fs.readFile(this.filePath, (err, data) => {
if (err) {
console.log(err);
}
cb(err, data) ;
});
}
}
In OrdersList you should use real file name and call function with callback to read file content: 在OrdersList中,您应该使用真实文件名和带有回调的调用函数来读取文件内容:
class OrdersList extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
let reader = new FileReader(realFilePath);
reader.getFileContent(',' , [], (err, content) => {
// TODO: file content in content var
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.