Uncaught TypeError: this.delete is not a function

2019-09-19 23:14发布

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>
    );
}
}

update the code, click save ,if the operate done . start to delete data , but now it appears error.
enter image description here Hello.tsx:36 Uncaught TypeError: Cannot read property 'delete' of undefined, I have seen the example TypeScript calling methods on class inside jquery function scope, i don't konw why that can run?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-19 23:58

Try

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));
}
查看更多
登录 后发表回答