当我为我的react组件编写测试用例时,我得到了
类型错误:无法分配给对象“#”的只读属性“x”
其中,当应用程序运行时,它不会抛出类似的错误
this.props. default = true;
为什么测试和实际应用程序运行的行为不同?如果我想写一个测试用例,应该怎么做?
z18hc3ub1#
有一种方法可以做到这一点;使用Object.assign()方法或JavaScript spread操作符创建对象的“clone”let clone = Object.assign({}, this.props);或let clone = { ...this.props };然后,更改所需的值并返回克隆结果。
let clone = Object.assign({}, this.props);
let clone = { ...this.props };
let clone = Object.assign({}, this.props); clone.defaultForm = true; return clone;
但是要考虑到Object.assign()创建了一个对象的浅拷贝。因此,如果你需要一个深拷贝,我建议使用以下方法:
let deepClone = JSON.parse(JSON.stringify(this.props)); deepClone.defaultForm = true; return deepClone;
在这里,“字符串化”对象,然后解析回来,将创建对象的全新深度克隆副本。
raogr8fs2#
syntax-punk答案JavaScript有一个内置的函数来创建任何对象的深层副本。
syntax-punk
const copiedObject = structuredClone(existingObject);
还有
let clone = { ...this.props }; //This doesn't create deep copy❌
JavaScript中的Spread运算符不会创建对象的深层副本
muk1a3rh3#
不能更改零部件的特性。它是只读。如果你想的话,可以改变它。必须使用connect from redux和函数mapStateToProps。您可以在这里找到更多信息:https://redux.js.org/basics/usage-with-react#implementing-container-components
connect
redux
mapStateToProps
3条答案
按热度按时间z18hc3ub1#
有一种方法可以做到这一点;
使用Object.assign()方法或JavaScript spread操作符创建对象的“clone”
let clone = Object.assign({}, this.props);
或
let clone = { ...this.props };
然后,更改所需的值并返回克隆结果。
但是要考虑到Object.assign()创建了一个对象的浅拷贝。因此,如果你需要一个深拷贝,我建议使用以下方法:
在这里,“字符串化”对象,然后解析回来,将创建对象的全新深度克隆副本。
raogr8fs2#
syntax-punk
答案JavaScript有一个内置的函数来创建任何对象的深层副本。
还有
JavaScript中的Spread运算符不会创建对象的深层副本
muk1a3rh3#
不能更改零部件的特性。它是只读。
如果你想的话,可以改变它。必须使用
connect
fromredux
和函数mapStateToProps
。您可以在这里找到更多信息:https://redux.js.org/basics/usage-with-react#implementing-container-components