在我的React组件中,我有一个文件输入:
<input type="file" onChange={this.onFileChange.bind(this)} />`
我的onFileChange
是:
onFileChange(e) {
let file = e.target.files[0];
this.setState(() => ({ file: e.target.files[0] })); //doesnt work
// this.setState(() => ({ file })); //works
// this.setState({ file: e.target.files[0] }); //works
}
设置状态的第一种方法失败,并显示错误:
Cannot read property 'files' of null
React还给出以下警告:
This synthetic event is reused for performance reasons. If you're
seeing this, you're accessing the property 'target' on a
released/nullified synthetic event
但是设置状态的最后两种方法没有给出错误或警告。为什么会这样呢?
该setState
函数在异步上下文中执行。
到状态更新时,e.target
引用可能会也可能不会消失。
const file = e.target.files[0];
可以像示例中那样“记住”该值。