我有一個用戶串列,我在一個小側欄中映射了它。可能沒有用戶。所以如果沒有用戶,我希望側邊欄說沒有。我嘗試了下面的方法,但它似乎仍在注冊用戶,即使它是 0。我已經嘗試過(user === null),(user.length < 1)但似乎無法得到它。
{usersList.map((user) => {
if (!user) {
return <h5>none</h5>;
} else {
return (
<h5
key={user}
>
<Link
to={`/user/${user}`}
style={{ textDecoration: "none"}}
>
{user}
</Link>
</h5>
);
}
})}
uj5u.com熱心網友回復:
檢查陣列長度是否大于0:如果是,則顯示串列,否則顯示“無”
你可以用一個簡單的三元運算子來做到這一點:
condition ? truthy : falsey
{usersList.length > 0 ? (
usersList.map((user) => (
<h5 key={user}>
<Link to={`/user/${user}`} style={{ textDecoration: "none" }}>
{user}
</Link>
</h5>
))
) : (
<h5>none</h5>
)}
uj5u.com熱心網友回復:
您可以使用三元運算子:
{
userList?.length > 0 ? <h5
key={user}
>
<Link
to={`/user/${user}`}
style={{ textDecoration: "none"}}
>
{user}
</Link>
</h5> :
<h5>No Users</h5>
}
或者可以使用&&
{(!userList || userList?.length === 0) && <h5>No Users</h5>}
{userList?.length > 0 && <h5
key={user}
>
<Link
to={`/user/${user}`}
style={{ textDecoration: "none"}}
>
{user}
</Link>
</h5>}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/337933.html
標籤:javascript 数组 if 语句 条件语句
上一篇:如何從包中添加新的構建操作
