gpt4 book ai didi

类方法中的 Javascript 变量不会持久存在

转载 作者:行者123 更新时间:2023-12-01 00:23:32 25 4
gpt4 key购买 nike

我正在 React 类中的表单上生成输入。输入将写入深度嵌套的 JSON 对象。当我生成每个输入时,我将一系列键作为数组传递,以帮助输入确定它应该在 JSON 对象中写入的位置。

示例['选项1','选项2',选项3]

{ 
option1: {
option2: {
option3: {}
}
}

这是我正在使用的实际类方法:

 generateNode(fields, path) {
return (
<NodeSection>
{Object.keys(fields).map(key => {
return this.generateInput(fields[key], path)
})}
</NodeSection>
);
}

现在,在generateInput 内部,我返回一个输入,其路径在onChange 方法中设置:

generateInput(input, path) { 
return (
<div>
<input value={this.getValue(input.name, path)}
onChange={e => {
this.setValue(e.target.value, input.name, path)
}} />
</div>
);
}

所以,问题是我想要一个输入,该输入将在路径的每个级别中设置一个值。因此,对于我作为路径传递的第一个输入:

 ['option1']

第二个输入我将其作为路径传递:

  ['option1', 'option2']

对于最终输入,我将其作为路径传递:

 ['option1', 'option2', 'option3']

但是当我尝试更改第一个输入(['option1'])上的数据时,它会通过

  ['option1', 'option2', 'option3']

???

我可以看到,当我通过父方法生成输入时,我传递了['option1']。但该值似乎会被接下来的两个方法调用/输入生成所覆盖。 setValue 每次在所有三个输入上都会传递 3 项数组。这会导致始终写入最内部的 JSON 对象级别。

我被困住了。有任何想法吗?

这里是设置值,如果有帮助的话。我可以告诉你,此时“path”已经是三项数组了。从日志中我可以看到它在最顶层的generateNode(我之前已经将路径永久打印在节点内)和generateNode之间发生了变化。当它到达generateNode时,传递的数组不再是函数中的数组。我怀疑是因为后来的电话。

setValue(value, name, path) {
const tree = this.state.treeLoadedForEditing;
const node = this.getNodeByPath(path);
if (node) {
node[name] = value;
}
this.setState({ treeLoadedForEditing: tree });
}

这是调用generateNode的方法:

generateNodeSections() {
const { treeLoadedForEditing, pathInView } = this.state;
if (treeLoadedForEditing.title) {
const nodeSections = [];
let currentPath = [];
let pathIdx = 0;
let currentTreeLevel = treeLoadedForEditing;
while(currentTreeLevel.node) {
const nodeData = this.getFieldDataFromRawNode(currentTreeLevel.node);
// generates the node at the given path
const node = this.generateNode(nodeData, currentPath);
nodeSections.push(node);
currentPath.push(pathInView[pathIdx]);
if (currentTreeLevel.children && Object.keys(currentTreeLevel.children).length) {
currentTreeLevel = currentTreeLevel.children[currentPath[currentPath.length - 1]]
} else {
// this stops the loops
currentTreeLevel = {};
}
pathIdx++;
}
return nodeSections;
}

}

最佳答案

By the time it hits generateNode, the array which was passed is no longer the array in the function.

事实上,事实恰恰相反。该数组始终与函数中的数组相同。数组不按值传递,而是按引用传递,这意味着一直传送到 setValuepath 是一个引用与您的 generateNodeSections 正在修改的完全相同的数组:

currentPath.push(pathInView[pathIdx]); 

每次将值推送到 currentPath 时,它都会修改每个 generateNode 以及每个 generateInput 所使用的数组,并且onChange。您应该传递数组的副本,而不是对原始数组的引用,如下所示:

const node = this.generateNode(nodeData, [...currentPath]); 

[...currentPath] 是创建数组浅拷贝的一种简短方法。这样,您将传递调用该​​函数时路径的不变快照。

关于类方法中的 Javascript 变量不会持久存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59203824/

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