我有一個組件,基本上可以作爲一個完全獨立的文件上傳。就目前而言,直到我獲得了上傳機制,我只是使用計時器來模擬進度變化。然而,當它達到100%,並嘗試發送消息給其父(通過statusChange
),我有一個範圍問題,其中this
是指window
。我怎樣才能解決這個問題?反應 - 用setInterval作用域問題
實際的錯誤:
Uncaught TypeError: _this.props.statusChange is not a function
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
整個時間確實是空的。
啊,該死!這是一個範圍問題。我會突出顯示如下:
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'直接在'componentDidMount'內是否正確?代碼對我來說似乎很好。 – loganfsmyth
是的,'console.info'打印就好了。奇怪的是,'if(this.state.progress === 100)'檢查也可以正常工作。我不明白。 – ffxsam
等等,這個錯誤實際上包括初步的下劃線?正如'_this.props.statusChange'? –