输入的event.target在this.setState中为null [React.js] [英] input's event.target is null within this.setState [React.js]

查看:79
本文介绍了输入的event.target在this.setState中为null [React.js]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的react组件中,我有一个文件输入:

In my react component I have a file input:

<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
}

第一种设置状态的方法失败,并显示以下错误:

This first way of setting the states fails with an error:

Cannot read property 'files' of null

反应还给出以下警告:

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

但是设置状态的最后两种方法没有给出错误或警告.为什么会这样呢?

But the last two ways of setting the state give no errors or warnings. Why is this happening?

推荐答案

setState函数在异步上下文中执行.

The setState function is executed in asynchronous context.

在状态更新时,e.target引用可能会也可能不会消失.

By the time the state is updated the e.target reference might or might not be gone.

const file = e.target.files[0];可以用来像示例中那样记住"该值.

const file = e.target.files[0]; can be used to "remember" the value as in your example.

这篇关于输入的event.target在this.setState中为null [React.js]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆