gpt4 book ai didi

javascript - 为什么传递给构造函数的数组与类不同步?

转载 作者:行者123 更新时间:2023-12-03 01:24:18 25 4
gpt4 key购买 nike

我认为您可以通过引用而不是值来访问属性,这是保持同步所必需的?

我有一个元素,并且正在传递一个 Refs 数组。当我 console.log() 时,它是一个空数组。但是如果我在 Controller 中使用 console.log() ,我可以看到它是一个引用数组。

每次点击(我看到这个输出):

[] <-- empty array inside ControlsController.  
[{ current: ... }, {...}] <-- correct output inside Controller.

为什么它不同步以及如何让它引用同一个数组?

class Controller extends React.Component<ControllerProps, ControllerState> {
public state = {
startIndex: 0,
endIndex: 6,
tempTestProp: ""
};

public itemRefs: Array<React.RefObject<HTMLLIElement | {}>> = [];

public generateRefs = memoize((children) => {
return Array.from({
......
}).map((_, index) => React.createRef());
});

public controlsController = new ControlsController({
element: this,
list: this.listRef,
items: this.itemRefs <------ here
});

public render() {
...........

.........

this.itemRefs = this.generateRefs(children);

return render({
......
itemRefs: this.itemRefs as Array<React.RefObject<HTMLLIElement>>,
.......
});
}

private handleControlClick = (direction: string) => (
event: React.MouseEvent<HTMLButtonElement>
) => {
console.log(this.itemRefs) // [ {..}, {..} .. ]
this.controlsController.move(event, direction);
};
}

这是我的 ControlsController

class ControlsController {

constructor({ ..., items, ... }: ConstructorProps) {
.....
this.items = items;
....
}
public move( ... ) {
switch (direction) {
case "next":
return moveNext.call(this);
}
}


function moveNext(this: ControlsControllerInterface) {
console.log(this.items); // []
}

最佳答案

JavaScript 数组和对象是 Java 意义上的引用,而不是 C/C++ 意义上的引用。这意味着“引用”是“引用”的缩写,它的行为类似于指针。所以在这一行:

this.itemRefs = this.generateRefs(children);

您正在使用不同的指针重新分配 itemRefs 引用值/指针,但 ControlsController 仍然具有指向原始空数组的相同指针。

由于这是 react 并且您正在处理状态更改,似乎您应该使 itemRefs 成为状态的一部分,然后在渲染内创建 ControlsController 。这样,当状态发生变化时,React 就会自动做正确的事情。

关于javascript - 为什么传递给构造函数的数组与类不同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com