如何在Reactjs中使用if else条件



我正在Reactjs和使用nextjs工作,现在我得到"cat_name"(类别)内映射函数(循环),我只是想添加条件"如果cat_name!="| | cat_name = ="pinned"在获取数据之前我怎么能做到这一点,这是我当前的代码

{students.data?.length > 0 &&
students.data.map((blog) => (
// 
{blog.cat_name}   // containing category,want to add condition here
if(blog.cat_name)
{
//further code
}
else
{
// further code
}
))}

您可以使用内联条件(三元操作符)来呈现其中一个。请注意,您只能返回一个JSX元素,这就是为什么您必须将它们包装在片段或div

中。
<>
{students.data?.length > 0 &&
students.data.map((blog) => (
<>
{blog.cat_name}
{blog.cat_name ? <>Either</> : <>Or</>}
</>
))}
</>;

引用:https://reactjs.org/docs/conditional-rendering.html inline-if-else-with-conditional-operator

你的代码刚刚好。如果您想使用您的语法,没有返回语句的箭头函数,您可以使用三元方法:

{students.data?.length > 0 &&
students.data.map((blog) => (
<> //fragment needed to wrap more than one node
{blog.cat_name ? <>Something</> : <>Something else</>}
</>
))}

或者你可以使用return语句,在其中你可以使用"default"if - else语句。

{students.data?.length > 0 &&
students.data.map((blog) => {
if(blog.cat_name)
{
return <>{blog.cat_name} <>anything else you want here</> </>
}
else
{
return <>{blog.cat_name} <>anything else you want here</> </>
}
})}

必须使用三元制条件:

{ condition ? a : b }

https://en.wikipedia.org/wiki/Ternary_conditional_operator

最新更新