当前位置: 首页 > 面试题库 >

输入的event.target在this.setState中为null [React.js]

胡曾笑
2023-03-14
问题内容

在我的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]; 可以像示例中那样“记住”该值。



 类似资料:
  • 除上述一种试验方法外,其他试验方法均有效并通过。我得到了。上面还提到了的实现。类是用Java编写的,而测试用例文件是用Kotlin编写的。

  • 我试图调整图像大小,首先我把我的输入流到缓冲的图像,然后使用这个缓冲图来缩放它 但是台词: 没有给出任何异常,只是在bim中返回null。为什么ImageIO不能读取我的输入流。我用这个流把它写在一个图像上,它工作得很好,但是当ImageIO读取它时,它返回null。我读到的地方,我需要传递文件对象,但为什么有一个选项,然后。有人能帮帮我吗。

  • 当我们有了前面知识的铺垫,就很容易理解this.setState的工作流程。 流程概览 可以看到,this.setState内会调用this.updater.enqueueSetState方法。 Component.prototype.setState = function (partialState, callback) { if (!(typeof partialState === 'ob

  • 问题内容: 我有以下课程片段: 我无法获得设置的超时值以从事件中打印值,我应该做些什么,但我不是吗? 问题答案: SyntheticEvent 。 根据 DOC : SyntheticEvent已合并。这意味着在调用事件回调之后,将重新使用SyntheticEvent对象,并且所有属性都将无效。这是出于性能原因。 例: 如何访问回调中的值? 将值存储在变量中: 如果要在超时回调函数中访问该值,则将

  • 我试图插入空数据,它必须出错,但它仍然在保存。如果为空,我尝试try/cath和if语句仍然不起作用。有人能建议如何做吗? 此图像中的输出RPCbloom 这个项目是带有GRPC和MyBatis的Spring Boot。