Javascript使用的是Call by Sharing,但我有个问题与React中的一些东西有关。
当你在函数中设置一个状态(setState Hook或Class State)时,会发生什么? 例如
const [myState, setMyState] = useState(null);
const foo = () => {
const bar = {'prop': 1};
setMyState(bar);
}
foo();
javascript是如何追踪在函数中设置的状态值的,因为据我所知: bar
死于非命 foo
.
setState是否会复制传递的值,还是我遗漏了什么?
值不会死。只要没有人过来把它们擦掉,值就永远躺在内存中(垃圾收集器)。然而,只要你在内存中有一个对该值的引用,垃圾回收器就不会去碰它。现在 bar
在你的情况下,包含对对象的引用。当你调用 setMyState
你通过引用,所以 setMyState
只要引用存在,就可以访问内存中的对象。最终react将该引用存储在某个地方,以将其返回给 myState
的引用。
// A very simplified version of useState:
let state; // the secret place were we keep the reference
function useState(initial) {
if(!state) state = initial;
function setState(value) { // here we get the reference
// food for thought: what happens to the object state referenced before here?
state = value; // and here we store it
render();
}
return [state, setState]; // here we pass on the reference to the render function
}
function render() {
const [counter, setCounter] = useState({ value: 1 }); // here we get a reference to the object
console.log(counter);
setTimeout(() => setCounter({ value: counter.value + 1 }), 1000); // and here we pass a new one in
}
render();
如果你不愿意传递引用,那么当执行 foo
结束,没有人可以访问 bar
了,因此没有人可以再访问躺在内存中的对象,因此垃圾收集器最终会过来。
以上都是谎言。在JavaScript中没有引用这种东西(好吧,有一个Reference ,但它在做别的事情),也没有内存这种东西。根据规范,值只是躺在 "某个地方"。现在,在实践中,引擎确实将值存储在内存中,因此,我说的一切或多或少对所有主流引擎都是正确的。