首页 > 解决方案 > Fat arrow functions in classes using old values after shallow clone (spread syntax)

问题描述

in a react-data-grid I'm using a typescript Class as my Row type. For better or for worse (worse it seems) I put a validation method onto the class because it made the code cleaner to put that responsibility right onto the class.

However my problem is that after data changes the validation method is using the old values of this.. It seems like the grid library reconstructs the row data upon each change. Below I have a simple reproduction of a similar issue, running a class function on a cloned object.

class Dog {
    name: string;
    bark = ():string => {
        return "hi, I am " + this.name;
    }

    constructor(name: string) {
        this.name = name;
    }
}

let bob = new Dog('bob');
console.log(bob.bark()); // hi, I am bob

const jill = {...bob, name: 'jill'}; // reproducing what I think react-data-grid is doing to my objects...  reassembling based upon their properties
console.log(jill.name); // jill
console.log(jill.bark());  // hi, I am bob - I expected jill

TS Playground link for the above.

What is going on here? I've been reading up on how object.assign works, and kinda see how that might cause the issue. Does the function member need to be re-created somehow?

标签: typescriptecmascript-6

解决方案


推荐阅读