【问题标题】: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>

javascript

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

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果您想在设置state 之后访问file

    你应该像这样使用它:

    this.setState({file} , () => {
        console.log(file, this.state.file)
    });
    

    @quidproquo 解释了为什么您在设置状态后没有立即访问它。

    将 setState() 视为请求而不是立即命令 更新组件。为了获得更好的感知性能,React 可能 延迟它,然后一次更新几个组件。反应 不保证立即应用状态更改。

    【讨论】:

      【解决方案2】:

      来自React.jsdocumentation

      setState() 视为更新组件的请求而不是立即命令。为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。 React 不保证立即应用状态更改。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-05
        • 2022-01-04
        • 2018-10-24
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        • 1970-01-01
        相关资源
        最近更新 更多