【发布时间】: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.logaftersetState永远不会显示更新的值 - 阅读文档 -
@xadm 为什么返回的字符串 this.state.myPicture 没有更新?
-
提示:
event.target.files[0]或类似...搜索处理上传/输入文件类型等。
标签: javascript reactjs redux file-io