this.setState(file) 之后 this.state.file 仍未定义 [重复]
Posted
技术标签:
【中文标题】this.setState(file) 之后 this.state.file 仍未定义 [重复]【英文标题】:this.state.file is still undefined after this.setState(file) [duplicate]this.setState(file) 之后 this.state.file 仍未定义 [重复] 【发布时间】:2018-04-03 12:35:10 【问题描述】:我遇到了这个奇怪的问题,我想不通。
我有一个按钮,点击后会出现一个文件窗口
当用户选择一个文件并单击确定时,我有this.setState(file)
记录用户选择的文件。但它不起作用。
<div id="file-upload-submit-btn-container">
<Button id="choose-file-btn"
onClick=this.buttonClick.bind(this)>
Choose file
</Button>
<input type="file" id="upload-input"
onChange=this.handleInputSelect.bind(this)
onClick=(e) => e.target.value = null // reset input file
multiple=false/>
</div>
constructor()
super()
this.state =
url: "https://example.com:8303",
getFileUploader()
return $(this.refs.dropzone).find("#upload-input")
buttonClick(e)
e.preventDefault()
let $fileuploader = this.getFileUploader()
$fileuploader.trigger('click');
handleInputSelect(e)
e.preventDefault()
let file = e.target.files[0]
this.setState(file) <---- setState at here, but it is not getting recorded
console.log(file, this.state.file) <---file IS defined here but not this.state.file, why?
this.handleUpload()
【问题讨论】:
【参考方案1】:如果您想在设置state
之后访问file
,
你应该像这样使用它:
this.setState(file , () =>
console.log(file, this.state.file)
);
@quidproquo 解释了为什么您在设置状态后没有立即访问它。
将 setState() 视为请求而不是立即命令 更新组件。为了获得更好的感知性能,React 可能 延迟它,然后一次更新几个组件。反应 不保证立即应用状态更改。
【讨论】:
【参考方案2】:来自React.js
documentation:
将
setState()
视为更新组件的请求而不是立即命令。为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。 React 不保证立即应用状态更改。
【讨论】:
以上是关于this.setState(file) 之后 this.state.file 仍未定义 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
在 this.setState 之后 Typeahead 文本输入未重置
AboutHeader.jsx:21 Uncaught TypeError: this.setState is not a function