Lỗi khó nhằn với từ khoá this trong typescript

private deletePhoto: (position, photoKey)=>void = (position, photoKey)=> {
        if (position.indexOf('cover') >= 0) {
            let size = position.replace('cover', '');
            size = size.charAt(0).toLowerCase() + size.slice(1);
            photoKey = photoKey.replace('.png', `-${size}.png`);
        }
        this.s3.deleteObject({Key: photoKey, Bucket: DefaultValue.BUCKET_NAME}, function (err, data) {
            if (err) {
                alert(err.message);
            }

            var confirmDelete = confirm("Delete image ?");

            if (confirmDelete == true) {
                this.setImage(position, DefaultValue.LINK_DF[position]);
            }

        });
    };

phía trên là code upload lên server amazon s3 . còn đây là hàm setImage . hàm nó bảo lỗi không phải là function

private setImage (position, link)=> {
        let linkReplace = {};
        linkReplace[position] = link;
        this.setState(linkReplace);
    };

nó hiểu this bên trong hàm this.s3.deleteObject là cái function callback . biết lỗi nhưng chưa biết cách sửa . anh em nào biết sửa giúp , thanks !!!

1 Like

khai báo 1 biến ngoài hàm = this rồi dùng biến đấy hoặc bạn có thể dùng arrow function cho callback

1 Like

cảm ơn bạn nhé , mình biết còn 1 cách khác là sửa callback thành hàm mũi tên , nhưng chưa hiểu cách đó lắm :smiley:

Hy vọng cái này là cái bạn đang muốn tìm:

private deletePhoto: (position, photoKey)=>void = (position, photoKey)=> {
        if (position.indexOf('cover') >= 0) {
            let size = position.replace('cover', '');
            size = size.charAt(0).toLowerCase() + size.slice(1);
            photoKey = photoKey.replace('.png', `-${size}.png`);
        }
        this.s3.deleteObject({Key: photoKey, Bucket: DefaultValue.BUCKET_NAME}, (err, data) =>  {
            if (err) {
                alert(err.message);
            }

            var confirmDelete = confirm("Delete image ?");

            if (confirmDelete == true) {
                this.setImage(position, DefaultValue.LINK_DF[position]);
            }

        });
    };

mình không rành TS lắm nhưng dù sao thì nó cũng được chuyển thành JS cả mà :smiley:

Mình sửa theo cách đó , nhưng chưa hiểu lắm . bạn có thể giải thích thêm được không .

arrow function == function.bind(this)

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?