typescript - 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?
解决方案
推荐阅读
- python - 在 django 中获取 404。甚至用户存在于数据库中
- amazon-web-services - 有没有办法将手动批准操作添加到 CdkPipeline?
- azure - 保护 AzureAD Powershell 模块
- vb.net - 尝试制作反复提出随机问题的数学游戏,如果你做对了,分数就会上升一分
- tensorflow - 如何识别模型的最后一层来进行迁移学习?
- csv - 创建 CSV 文件以从 Internet 读取
- python - 如何解决python中的列表索引错误?我不明白
- http - http上下文中二进制和文本协议的区别
- python - 如何进入 VS Code 用于 pylance 的环境?
- c++ - 在合并排序中出现错误。有人可以帮我找出错误吗?