【问题标题】:Break map loop inside return in component在组件的返回中打破地图循环
【发布时间】:2022-01-09 23:34:55
【问题描述】:

我正在尝试循环进入一个数组以创建组件内容,如果不满足数组元素的条件,则中断循环并返回 1 个组件

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

这是我目前的代码,每次 leave.id 与 currentUser 的 id 不同时都不会打印出任何叶子

我需要做的是,仅当没有叶子的 id 与当前用户的 id 匹配时才打印不打印叶子,因此我想在打印没有叶子后破坏地图

【问题讨论】:

    标签: javascript reactjs loops


    【解决方案1】:

    您应该使用Array.prototype.some。在您的情况下,您将向该方法传递一个函数以检查它是否满足您的条件并使用三元运算符来呈现内容。

    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}`);

    【讨论】:

    • 这很好,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-11-09
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多