【问题标题】:how to setState with a file object如何使用文件对象设置状态
【发布时间】:2019-02-06 08:08:56
【问题描述】:

我有一个需要放入状态的文件对象。我尝试这样做的原因是它被提供为重新渲染 DOM 以清除 FileReader() 中的值的可能解决方案。这是当前线程源自的链接

Node 'crypto' SHA256 hashing model behaving erratically

我将在此处放置一个精简的 react 组件,以便您查看发生了什么。

import React, { Component } from "react";

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      files: []
    };
  }

  onChange(e) {
    let files = e.target.files;
    this.setState({ files: files[0] });
    console.log(files[0]);
    console.log(this.state.files)
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>
    );
  }
}

export default SearchPage;

console.log(files[0]} 给出如下内容:

File(1) {name: "1.txt", lastModified: 1549429792266, lastModifiedDate: Tue Feb 05 2019 22:09:52 GMT-0700 (Mountain Standard Time), webkitRelativePath: "", size: 1, …}
lastModified: 1549429792266
lastModifiedDate: Tue Feb 05 2019 22:09:52 GMT-0700 (Mountain Standard Time) {}
name: "1.txt"
size: 1
type: "text/plain"
webkitRelativePath: ""

如果我console.log(this.state.files) 我得到[]

我已将初始状态设置为""null 无济于事。我最终想将状态用于FileReader() 函数。

感谢任何想法或解决方案。谢谢!

【问题讨论】:

    标签: reactjs state


    【解决方案1】:

    setState 是一个异步函数,你需要在setState 的回调函数内记录控制台日志,该回调函数在状态更新后执行。

    onChange(e) {
      let files = e.target.files;
      this.setState({ files: files[0] }, () => { console.log(this.state.files) });
      console.log(files[0]);
    
    }
    

    【讨论】:

      【解决方案2】:

      这里 Files[0] 是一个对象,如果您只是将状态文件类型更改为空对象并在渲染方法中控制状态变量,那么您将该对象存储在数组中,因为值将更新。 这是一个例子:

      this.state = {
        files: {}
      };
      render() {
        console.log(this.state.files)
        return (
        --- 
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2019-12-27
        • 1970-01-01
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 2016-04-29
        • 2019-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多