简体   繁体   English

在组件返回内部断开 map 回路

[英]Break map loop inside return in component

I'm trying to loop into an array to create the component content, if condition on array element is not satisfied then break the loop and return 1 component我正在尝试循环进入一个数组以创建组件内容,如果不满足数组元素的条件,则中断循环并返回 1 个组件

leaves.map(leave => leave.id === currentUser.id ? <div> {leave} </div> : <div> no leaves </div>)

This is the code I have so far, no leaves is printed out every time leave.id is different than currentUser's id这是我到目前为止的代码,每次 leave.id 与 currentUser 的 id 不同时都不会打印出任何叶子

What I need to is, print no leaves only when none of the leaves's id matches the currentUser's id and therefore I want to break the map after printing no leaves我需要的是,仅当没有叶子的 id 与 currentUser 的 id 匹配时才打印没有叶子,因此我想在打印没有叶子后打破 map

You should use Array.prototype.some .你应该使用Array.prototype.some In your case, you would pass a function to the method to check whether it satisfies your condition and use the ternary operator to render the content.在您的情况下,您会将 function 传递给该方法以检查它是否满足您的条件并使用三元运算符来呈现内容。

 const arrWithId = [670760658, 250026214, 126834449, 987103760, 882536150, 666896331, 488576796, 186598055, 103751309, 419995457, 503676712, 487691896, 744253979, 269253696, 102370148, 237328910, 409016979, 979651614, 743486466, 445993562, 779323321, 939834768, 296731253, 925812473, 114149678]; const arrWithoutId = [123456789, 250026214, 126834449, 987103760, 882536150, 666896331, 488576796, 186598055, 103751309, 419995457, 503676712, 487691896, 744253979, 269253696, 102370148, 237328910, 409016979, 979651614, 743486466, 445993562, 779323321, 939834768, 296731253, 925812473, 114149678]; const id = 123456789; const checker = elem => id === elem; console.log(`With ID: ${arrWithId.some(checker)? "yes": "no"}`) console.log(`Array: ${arrWithId}`); console.log(`Without ID: ${arrWithoutId.some(checker)? "yes": "no"}`) console.log(`Array: ${arrWithoutId}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM