反应本机:嵌套的json对象浅副本(参考)不起作用
我有一个嵌套的JSON对象,看起来像{“ name”,“ children”:[JSON对象]}
。 我正在尝试将一个新孩子添加到带有变量路径
的对象中,该名称数组。
我的代码在我的React Native应用程序中不起作用,但是它在Chrome控制台中确实如此,这使我真的很困惑。它与反应本地有关吗?如果是这样,我该如何解决?
在Google控制台上载的代码产生了预期的结果:J.Children [0] .Children [0] ='test'
:
let j = {"name": "root", children: [{"name": "tag1", children: []}]};
let res = j;
const path = ["tag1"];
for (const name of path) {
for (const child of res.children) {
if (child.name == name) {
res = child;
break;
}
}
}
res.children.push("test");
console.log(j);
相同的代码,包裹在React Native App中,在Android上进行了测试模拟器(Pixel_5_API_30),产量 {“儿童”:[{“ children”:[array],“ name”:“ tag1”}],“ name”:“ root”}
不是预期的行为(>
> [数组]
表示空数组)。
export default function App() {
const test = () => {
let j = {"name": "root", children: [{"name": "tag1", children: []}]};
let res = j;
const path = ["tag1"];
for (const name of path) {
for (const child of res.children) {
if (child.name == name) {
res = child;
break;
}
}
}
res.children.push("test");
console.log(j);
}
return (
<View>
<Button title="test" onPress={test} />
<StatusBar style="auto" />
</View>
);
}
I have a nested JSON objects that looks like {"name", "children": [JSON objects]}
.
I am trying to add a new child to the object found with a variable path
, an array of names.
My code doesn't work in my React Native app, however it does in the Chrome console, which makes me really confused. Does it have to do with React Native and if so how can i work it out ?
Code uploaded in the Google Console which yields the expected result : j.children[0].children[0] = 'test'
:
let j = {"name": "root", children: [{"name": "tag1", children: []}]};
let res = j;
const path = ["tag1"];
for (const name of path) {
for (const child of res.children) {
if (child.name == name) {
res = child;
break;
}
}
}
res.children.push("test");
console.log(j);
The same code, wrapped in a React Native app, tested on an Android emulator (PIXEL_5_API_30), yields{"children": [{"children": [Array], "name": "tag1"}], "name": "root"}
which is not the expected behavior ([Array]
means empty array).
export default function App() {
const test = () => {
let j = {"name": "root", children: [{"name": "tag1", children: []}]};
let res = j;
const path = ["tag1"];
for (const name of path) {
for (const child of res.children) {
if (child.name == name) {
res = child;
break;
}
}
}
res.children.push("test");
console.log(j);
}
return (
<View>
<Button title="test" onPress={test} />
<StatusBar style="auto" />
</View>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,检查后,确实
[array]
不是空数组,并且代码按预期工作。似乎反应本机仅显示阵列最高为一个深度。Okay after checking, indeed
[Array]
is not the empty array, and the code works as intended. It seems React Native only display array up to one depth.