[英]React map unexpected behaviour
I've got this function in my Global.jsx
file: 我的Global.jsx
文件中有此功能:
FeGruHasChilds: (childs) => {
childs.map((c, i) => {
if (c.VALUEDB != null && c.VALUEDB != "") {
console.log(c.VALUEDB);
return true;
}
});
}
I'm calling it like this: 我这样称呼它:
Global.FeGruHasChilds(myArray) &&
myArray.map((c, i) =>{
<MyComponent value=myArray[i].VALUEDB/>
})
My expected behaviour is, that if any item in myArray
has an VALUEDB
then FeGruHasChilds
should return true
and quit the function and react should render MyComponent
for every item in myArray
. 我的预期行为是,如果myArray
中的任何项目都具有VALUEDB
则FeGruHasChilds
应该返回true
并退出该函数,并且应为myArray
每个项目渲染MyComponent
。
Actual behaviour: The function doesn't quit if there is an item with VALUEDB
, it does check it for all items (I logged it in the console). 实际行为:如果存在带有VALUEDB
的项目,该函数不会退出,它会检查所有项目(我在控制台中将其记录下来)。 And also there is never any MyComponent
rendered. 而且,永远不会呈现任何MyComponent
。 It's always empty. 它总是空的。
EDIT: tried to execute it like this: 编辑:试图执行它是这样的:
<button onClick={() => console.log(Global.FeGruHasChilds(myArray))}>TEST</button>
It returns undefined
返回undefined
When you want to return true
if any of the items passes a test, you can use Array.some()
: 如果任何一项通过测试都想返回true
则可以使用Array.some()
:
FeGruHasChilds: (childs) =>
childs.some(c => c.VALUEDB !== null && c.VALUEDB !== ""); // c => c would be enough if you have strings or null
In your case Array.map()
returns an array of true
and false
. 在您的情况下, Array.map()
返回true
和false
的数组。 An array by itself is a truthy value, and should have caused the components to be rendered all them time. 数组本身是一个真实的值,应该已经使组件在所有时间上都呈现出来。 However, you don't return the result from the function, and the function always returns undefined
. 但是,您不会从该函数返回结果,并且该函数总是返回undefined
。 Undefined is a falsy value, so the components never render. 未定义是虚假的值,因此组件永远不会渲染。 You can return the value by using the return
key word, or just remove the curly brackets of the arrow function: 您可以使用return
关键字来返回值,或者只需移除arrow函数的大括号即可:
FeGruHasChilds: (childs) => {
childs.map((c, i) => { // not returned
if (c.VALUEDB != null && c.VALUEDB != "") {
console.log(c.VALUEDB);
return true;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.