成功上传文件后,我正在尝试更新父组件中的状态。文件成功上传,并且Promise已按预期执行。
问题是出现以下错误:
TypeError:无法读取未定义的属性“操作”
在线:
promise.then(this.props.action())
如何解决此错误并更新父组件中的状态?
class FileUploadWidget extends Component {
componentDidMount() {
var self=this;
let fileName = this.props.file
let payrollID = this.props.payrollID
const inputElement = document.getElementById(this.props.file);
if(inputElement){
inputElement.addEventListener("change", handleFiles, true);
}
function handleFiles() {
const self = this;
const fileList = this.files;
const uri = "******/fileupload.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();
const promise = new Promise(function(resolve, reject) {
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve("Success")
}
if (xhr.readyState == 4 && xhr.status == 400) {
alert(xhr.responseText);
}
};
fd.append('myFile', fileList[0]);
fd.append('fileID', fileName)
fd.append('payrollID', payrollID)
fd.append('origionalFileName', fileList[0]["name"]);
xhr.send(fd);
})
promise.then(this.props.action())
}
}
render() {
return (
<div>
<input type="file" id={this.props.file}></input>
</div>
)
}
}
父项:
class UploadRequired extends Component {
constructor(props) {
super(props);
this.state = {status: ""};
this.handler = this.handler.bind(this);
}
handler() {
console.log("State set!!")
this.setState({
state: "0"
});
}
componentWillReceiveProps = props => {
this.setState({ status : props.dataRow });
}
render() {
var button = <div></div>;
if(this.state.status == ""){
button = <FileUploadWidget file={this.props.file} payrollID={this.props.payrollID} action={() => this.handler()}/>;
}
if(this.state.status == "0"){
button = <ProcessWidget />;
}
if(this.state.status == "1"){
button = <ProcessingWidget />;
}
if(this.state.status == "2"){
button = <ProcessedWidget />;
}
return(
<div>
{button}
</div>
)
}
}
export default UploadRequired;
答案 0 :(得分:0)
您可能需要将this
绑定到您的方法。
尝试使用箭头功能:
inputElement.addEventListener("change", () => handleFiles(), true)
或者在构造函数中使用经典绑定,并使其成为类函数:
constructor () {
this.handleFiles= this.handleFiles.bind(this)
}
function componentDidMount () { ... }
function handleFiles () { ... }
编辑:
即使通过IMO看起来不是很好,即使想到通过this
作为上下文的第三种选择:
inputElement.addEventListener('change', () => handleFiles(this), true)
function handleFiles (context) {
// ...
promise.then(context.props.action())
}