[英]React - Scoping issue with setInterval
我有一个组件,基本上可以用作要上传的完全独立的文件。 就目前而言,在我建立上载机制之前,我只是使用计时器来模拟进度更改。 但是,当它达到100%并尝试向其父级发送一条消息(通过statusChange
)时,我遇到了一个范围限定问题, this
问题涉及到window
。 我怎样才能解决这个问题?
实际错误:
未捕获的TypeError:_this.props.statusChange不是函数
componentDidMount() {
this.timer = setInterval(() => {
this.setState({progress: this.state.progress + 5});
if (this.state.progress === 100) {
clearInterval(this.timer);
this.props.statusChange({uploadComplete: true});
}
}, 1000);
debugMode && console.info('[FileUpload] Began uploading %s',
this.props.name);
},
编辑:问题似乎出在回调的传递中。 实际上, this.props.statusChange
为null。
啊,该死! 这是一个范围界定的问题。 我将在下面突出显示它:
UploadQueue = React.createClass({
displayName: 'UploadQueue',
propTypes: {
fileList: React.PropTypes.any.isRequired
},
statusChange(status) {
debugMode && console.info('[UploadQueue] Status change! %o', status);
},
render() {
let files = [];
// Convert to a true array
for (let i = 0; i < this.props.fileList.length; ++i) {
files = files.concat(this.props.fileList[i]);
}
return (
<div>
{files.map(function (file) { // should be: {files.map(file => {
return <FileUpload key={file.name}
name={file.name}
statusChange={this.statusChange} />
})}
</div>
)
}
});
this
范围问题是在拥有FileUpload
的组件中。 下面的固定代码。
{files.map(file => {
return <FileUpload key={file.name}
name={file.name}
statusChange={this.statusChange} />
})}
尝试这个:
componentDidMount() {
this.timer = setInterval(() => {
this.setState({progress: this.state.progress + 5});
if (this.state.progress === 100) {
clearInterval(this.timer);
this.props.statusChange({uploadComplete: true});
}
}.bind(this), 1000);
^^^^^^^^^^^^
debugMode && console.info('[FileUpload] Began uploading %s',
this.props.name);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.