简体   繁体   English

JSX 不与地图功能一起在条件渲染上渲染

[英]JSX doesn't render on conditional render alongside with map function

I want to render a component based on a variable being true or false.我想根据变量为真或假来呈现组件。 At the moment the condition comes up as true but the component isn't rendering at all.目前条件为真,但组件根本没有渲染。

Here is my code:这是我的代码:

<div className={styles.container}>
   {array.map(item => {
    router.query.slug != item ? <Component /> : null;
    })}
</div>

My console is returning true for the condition router.query.slug != item so what am I missing?我的控制台为条件router.query.slug != item返回 true 那么我错过了什么?

Thanks谢谢

You are missing to return the component from map function.您缺少从 map 函数返回组件。

Here is the example that will match your problem:这是与您的问题相匹配的示例:

Solution 1解决方案1

<div className={styles.container}>
    {array.map(item => {
        return router.query.slug != item ? <Component /> : null;
    })}
</div>

Solution 2 with single line解决方案 2单行

<div className={styles.container}>
    {array.map(item => router.query.slug != item ? <Component /> : null)}
</div>

You can read about map function in here.您可以在此处阅读有关map功能的信息。

If you use the block syntax, you need to specify the return keyword.如果使用block语法,则需要指定 return 关键字。 Learn more about arrow-function了解有关箭头函数的更多信息

Try this way.试试这个方法。

Example:例子:

<div className={styles.container}>
   {array.map(item => {
     return (router.query.slug != item ? <Component /> : null)
    })}
</div>

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

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