【问题标题】:handleInputChange - React Redux File UploadhandleInputChange - React Redux 文件上传
【发布时间】:2020-02-02 20:36:22
【问题描述】:

我正在尝试上传文件并使用已上传的文件对象更新状态。

setState 后的控制台日志显示状态尚未更新。

每当我尝试 console.log 文件上传 onChange 的事件时,我都会得到一个循环 JSON 引用,如果我尝试记录 event.target,我会得到未定义。

如何将上传的文件写入状态?

import React, { Component } from "react";
import { connect } from "react-redux";
import Button from "@material-ui/core/Button";

class FileUpload extends Component {

  state = {
    myPicture: {}
  };

  handleInputChange = (event) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });

    console.log(JSON.stringify(this.state))
    console.log(JSON.stringify(this.props))

  }

  render() {
    const {myPicture} = this.props;

    return (
      <div>

        {JSON.stringify(this.state.myPicture)}

        <input
          accept="image/*"
          className={"fileInput"}
          id="myPicture"
          multiple
          type="file"
          onChange={this.handleInputChange}
        />
        <label htmlFor="myPicture">
          <Button variant="contained" color="primary" component="span">
            Upload Picture
          </Button>
        </label>
        </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    myPicture: state.auth.myPicture,
  };
}

export default connect(mapStateToProps)(FileUpload);

【问题讨论】:

  • console.log after setState 永远不会显示更新的值 - 阅读文档
  • @xadm 为什么返回的字符串 this.state.myPicture 没有更新?
  • 提示:event.target.files[0] 或类似...搜索处理上传/输入文件类型等。

标签: javascript reactjs redux file-io


【解决方案1】:

您不能直接引用文件数组或文件本身。

您必须引用 event.target.files[0] 中的特定键。

文件上传后的例子:

  • 例如:JSON.stringify(event.target.files[0]) === {}
  • 例如:JSON.stringify(event.target.files[0].name === 'myFileNameHere'

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2021-07-12
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多