0%

FileReader 的 onload 方法的一个问题

今天写可视化的代码,首先要加载 CSV 文件,使用 FileReader 来加载,然后用 d3 来解析 csv,然而出现了一个问题。
像下面这样写就会报错,
Uncaught TypeError: Cannot read property 'length' of undefined
我输出文件长度,发现其值为 0,d3 无法解析所以报错。

1
2
3
4
5
let readFile = file => {
let r = new FileReader();
r.readAsText(file, config.encoding);
r.onload = () => console.log(d3.csvParse(this.result));
};

改成这样就行了,不知道为什么。

1
2
3
4
5
6
let readFile = file => {
...
r.onload = function () {
console.log(d3.csvParse(this.result))
}
};

Welcome to my other publishing channels