我有一个处于反应性状态的类实例,如下所示:
class Room {
name;
participant;
constructor(name) {
this.name = name;
this.participant = {
screensharing: false,
};
}
sendReinvite() {
console.log("reinvite");
}
}更改屏幕共享并使用扩展运算符进行状态变异后,sendReinvite方法将被删除,并在第二次单击时导致错误:
const SpreadOperator = () => {
const [room, changeRoom] = useState(new Room());
const toggleScreenSharing = () => {
console.log("room", room);
room.participant.screensharing = !room.participant.screensharing;
room.sendReinvite();
changeRoom({...room});
};
return (
<div>
<h1>spread operator</h1>
<button onClick={toggleScreenSharing}>Screen share</button>
</div>
);
};
export default SpreadOperator;错误: Uncaught : room.sendReinvite不是一个函数--如何在不丢失方法的情况下更改屏幕共享,顺便说一句,这个实例来自某个库,我无法更改它,
就像一个真实的:
发布于 2022-08-11 18:22:01
不要在类实例中使用扩散运算符。
检查此链接以查看为什么我不能在类函数上使用扩展运算符?
考虑以下片段:
class A {
constructor() {
this.a = 'a', this.b = 'b'
}
mymethod() {
return true
}
}如果你这样做了:
const a = new A();
a.mymethod(); // true如果你在里面使用扩展操作符:
const a = new A();
const b = { ...a };
b.mymethod(); // b.mymethod is not a function
b.a; // 'a'不要直接修改您的状态
再说一遍,为什么我不能直接修改组件的状态呢?
你这样做是因为:
room.participant.screensharing = !room.participant.screensharing;因此,替换:
room.participant.screensharing = !room.participant.screensharing;
room.sendReinvite();
changeRoom({...room});通过以下方式:
const myNewRoomState = new Room(); // Create another state object
myNewRoomState.participant.screensharing = !room.participant.screensharing;
myNewRoomState.sendReinvite();
changeRoom(myNewRoomState);这仍然值得怀疑,因为您正在使用可变类实例来存储不可变状态,我建议您检查这个帖子:是否有一种将可变类实例对象存储在状态中的反应方式?。
但总括而言:
changeRoom函数(它是负责更改您的房间状态的函数)更改它的属性。发布于 2022-08-11 18:24:34
亚历克斯在回答这个问题上做得很好,但我想补充一些东西来帮助你更好地理解。
sendReinvite存在于Room.prototype中,而做{...rom}并不能克隆原型。
https://stackoverflow.com/questions/73324952
复制相似问题