[英]How can I put the value of the array object using useState when rendering for the first time in Reactnative?
I have an object array called targetFarm, and when I run the map function, the value comes out like this.我有一个名为 targetFarm 的 object 数组,当我运行 map function 时,值是这样的。
targetFarm.children.map((item) => item.children.map((v) => console.log("v:", v)));
v = {
name: "coffee"
}
v = {
name: "tea"
}
v= {
name: "icecream"
}
What I want to do is put the value of this v.name in an array form using useState in the box constant.我想要做的是使用 box 常量中的 useState 将此 v.name 的值放入数组形式中。 as below
如下
box = [
"coffee",
"tea",
"icecream",
]
But when I used my code This error pops up.但是当我使用我的代码时会弹出此错误。
"Cannot read property 'push' of undefined" “无法读取未定义的属性‘推送’”
const [box, setBox] = useState(
targetFarm.children.map((item) => {
item.children.map((v) => {
box.push(v.name)
})
})
)
then How can i fix my code?那么我该如何修复我的代码?
What I want to do is put the value of this v.name in an array form using useState in the box constant
我想要做的是使用 box 常量中的 useState 将此 v.name 的值放在数组形式中
You can use map
and flatMap
like below您可以使用
map
和flatMap
如下
targetFarm.children.flatMap((item) => item.children.map((v) => v.name);
"Cannot read property 'push' of undefined"
“无法读取未定义的属性‘推送’”
From your code, box
has not been initialized yet, so undefined
does not have push
method.从您的代码中,
box
尚未初始化,因此undefined
没有push
方法。 That's why it's throwing that error.这就是它抛出该错误的原因。
If you want to assign the default state value for box
, you can check the below example.如果要为
box
分配默认的 state 值,可以查看以下示例。
const [box, setBox] = useState(
targetFarm.children.flatMap((item) =>
item.children.map((v) => v.name)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.