2017-04-10 42 views
0

最初我使用按鈕呈現Upload file文本。點擊此按鈕後,它調用_handleSubmit將文件發送到API。
發送完成後,我想更改Upload fileto Upload done。爲此,我創建了一個變量isSend但無法使用它。發送數據後更改頁面的視圖

_handleSubmit(e) { 
    e.preventDefault(); 
    const fl = new FormData(); 
    fl.append("name", this.state.file); 
    const req = request 
     .post("/upload") 
     .send(fl); 
    req.end(function (err, response) { 
     if (response=== "OK") { 
     this.setState({//not setting showing error 
      isSend: true 
     }); 
     } 
    }); 

    } 



render() { 
    const isSend = this.state.isSend; //false initially 
    return (
     <div> 
      <h3>Upload file</h3> //Show done upload after done 

      <button 
        type="submit" 
        onClick={(e) => this._handleSubmit(e)}>Upload File 
      </button> 
     </div> 

    ) 
    } 

回答

1

你忘了bindcontext,使用此:

req.end((err, response) => { 
    if (response=== "OK") { 
     this.setState({ //it will work 
      isSend: true 
     }); 
    } 
}); 

或使用.bind(this)有回調方法,像這樣:

req.end(function(err, response) { 
    if (response=== "OK") { 
     this.setState({ //it will work 
      isSend: true 
     }); 
    } 
}.bind(this)); 

,並檢查isSend裏面的值渲染方法改變文字,如下:

render() { 
    const isSend = this.state.isSend; //false initially 
    return (
     <div> 
      <h3> {isSend ? 'Upload Done' : 'Upload file' } </h3> 
      <button 
       type="submit" 
       onClick={(e) => this._handleSubmit(e)}>Upload File 
      </button> 
     </div> 

    ) 
}