Javascript 向箭头函数添加条件
我有下面的代码片段Javascript 向箭头函数添加条件,javascript,Javascript,我有下面的代码片段 {categoriesWithSub.length > 0 && categoriesWithSub.map(item => { //Add new condition here const pageChanges = { catId: item.id, catName: item.catName, }; return ( <Tile
{categoriesWithSub.length > 0 &&
categoriesWithSub.map(item => {
//Add new condition here
const pageChanges = {
catId: item.id,
catName: item.catName,
};
return (
<Tile
to="./request"
text={item.catName}
key={item.id}
onClick={() => handleChange('departments', pageChanges)}
/>
);
})}
我试过了,但语法有问题:
{categoriesWithSub.length > 0 &&
categoriesWithSub.map(item => {
item.subCategories.length > 0 ?(
const pageChanges = {
catId: item.id,
catName: item.catName,
};
return (
<Tile
to="./request"
text={item.catName}
key={item.id}
onClick={() => handleChange('departments', pageChanges)}
/>
);
):
retrun (
<Tag
text={''}
to="../exact-request"
key={0}
onClick={() => handleChange('request', '')}
/>
)
})}
我不确定我是否完全得到了你想要的,但是你可以在那里添加条件。但我要说的是,在渲染中这样做是不好的做法,在渲染中,您应该渲染这应该是一个函数或组件 { 子长度>0的类别&& categoriesWithSub.mapitem=>{ 如果item.subCategories.length>0{ 归还某物 } 归还某物 }
} 如果为false,则可以在开始时返回该条件:
{categoriesWithSub.length > 0 &&
categoriesWithSub.map(item => {
const someCondition = <...>
if (!someCondition) return false;
// rest of your code
这有点奇怪,但很简单:
return item.subCategories.length > 0 ?
(
<Some ... />
) :
(
<Tag
text={''}
to=../exact-request
key={0}
onClick={() => handleChange('request', '')}
/>
);
但我建议您这样编写代码:
if (item.subCategories.length > 0) {
return <Some ... />
}
return (
<Tag
text={''}
to=../exact-request
key={0}
onClick={() => handleChange('request', '')}
/>)
您的代码必须可读Ternaries用于表达式,return不是表达式。可以只使用if?return item.subCategories.length>0;但如前所述,if语句是实现这一点的方法。三元条件不应以这种方式使用。它们期望在它们内部有一个表达式,并且它们应该只用于简单的条件,如a>b?a:b。虽然它们看起来很酷,但我建议你使用老式的if语句。谢谢大家的评论,我很乐意学习。
return item.subCategories.length > 0 ?
(
<Some ... />
) :
(
<Tag
text={''}
to=../exact-request
key={0}
onClick={() => handleChange('request', '')}
/>
);
if (item.subCategories.length > 0) {
return <Some ... />
}
return (
<Tag
text={''}
to=../exact-request
key={0}
onClick={() => handleChange('request', '')}
/>)