我正在尝试使用onload函数中的fileList.push({link:href})
将链接添加到我的状态。问题是for循环运行了x次,然后又运行了所有onloads,并且仅获取所选文件的最后一项。我尝试使用IIFE,但是没有用。这是我的代码:
class Download extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this);
this.inputRef = React.createRef();
this.state = {
files: [],
}
}
handleClick = () => {
const node = this.inputRef.current;
const self = this;
let file;
let name;
let href;
let reader;
node.addEventListener('change', function() {
const fileList = [];
for(let x = 0, xlen = this.files.length; x < xlen; x++) {
file = this.files[x];
name = file.name;
console.log(name);
fileList.push({name:name});
if(file.type.indexOf('audio/mp3') != -1) {
reader = new FileReader();
reader.onload = (e) => {
href = e.target.result;
fileList.push({link:href});
}
};
reader.readAsDataURL(file);
}
self.setState({ files: fileList });
console.log(self.state)
// console.log(self.state);
});
};
//PLAYLIST
render() {
return(
<div className="input">
<input onClick={this.handleClick} id="upload-file" className="inputName" type="file" multiple ref={this.inputRef}/>
<div>
<ReactAudioPlayer
id="audio"
src="my_audio_file.ogg"
autoPlay
controls
/>
<ul ref={this.ulRef}>
{this.state.files.map((file, index) => (
<li key={index}><Link to={file.link}>
{file.name}
</Link></li>
))}
</ul>
</div>
<output id="list"></output>
</div>
)
};
}
export default Download;
我已经调整了上面的代码,并在此处发布了一个示例:
https://codesandbox.io/s/laughing-bird-hfuf5
我从上面的代码中删除了一些组件特定的详细信息,以说明解决方案。我认为这里的技巧是将文件(FileList)转换为数组:
let files = Array.from(event.target.files);
我希望这会有所帮助!
最好,山姆