2017-10-19 71 views
-1
import * as React from "react"; 
import $ = require("jquery"); 


export class Hello extends React.Component<{}, {}> { 
public delete() { 
    console.log("delete"); 
    $.ajax({ 
     type: "DELETE", 
     url: "http://127.0.0.1:8080/delete", 
     xhrFields: {withCredentials: true} 
    }).done((data: any): void => { 
     console.log("delete data:" + data); 
    }).fail((jqXHR: any): void => { 
     console.log("delete faildata: " + jqXHR.status); 
    }); 
} 


public save() { 
    console.log("save"); 
    $.ajax({ 
     type: "POST", 
     url: "http://127.0.0.1:8080/save", 
     dataType: "text", 
     crossDomain: true, 
     xhrFields: {withCredentials: true} 
    }).done((data: any): void => { 
     console.log("data:" + data); 
     {this.delete()} 
    }).fail((jqXHR: any): void => { 
     console.log(jqXHR); 
     console.log("faildata: " + jqXHR.status); 
    }); 
} 
render() { 
    return (
     <div> 
      <button onClick={this.delete}>delete</button> 
      <button onClick={this.save}>save</button> 
     </div> 
    ); 
} 
} 

更新代碼,點擊保存,如果操作完成。開始刪除數據, 但現在它出現錯誤。
enter image description here Hello.tsx:36 Uncaught TypeError:無法讀取未定義的屬性'delete',我已經看過示例TypeScript calling methods on class inside jquery function scope,我不知道爲什麼可以運行?Uncaught TypeError:this.delete不是函數

+0

'this'內完成'()'和'失敗()'處理程序不會不管外部範圍你期待它來指代。鑑於你的代碼示例,你甚至不需要'this'引用。 –

+0

upadte我的代碼,你能幫助我嗎? – ziqi

+0

不是真的,因爲你還沒有解釋你所期望的'this'是否參考 –

回答

0

嘗試

private save() { 
    console.log("save"); 
    $.ajax({ 
     type: "POST", 
     url: "http://127.0.0.1:8080/save", 
     dataType: "json", 
     crossDomain: true, 
     xhrFields: {withCredentials: true} 
    }).done((function (data) { 
     console.log("data:" + data); 
     this.delete(); 
    }).bind(this)).fail((function (jqXHR:any) { 
     console.log("faildata: "+jqXHR.status) 
     this.delete(); 
    }).bind(this)); 
} 
+0

它不起作用,Hello.tsx:45 Uncaught TypeError:無法讀取屬性'delete'undefined – ziqi

相關問題