JS 只根据条件执行 if 语句

时间:2021-02-04 04:33:18

标签: javascript

我正在从 api 获取数据,我需要根据 if 语句呈现组件,但我似乎无法弄清楚。客户具有一系列角色。 Customer.items 是一组客户对象。这是我正在尝试但不起作用的 if 语句:

{customers?.items?.length > 1 && !roles.includes("Super") && (...component

基本上我需要检查roles数组是否有“Super”并且customers.items只有一个元素然后不渲染组件。

如果角色是“超级”并且 customer.items.length > 1 那么仍然渲染组件

customers.items: [{id: 2, name: "G"}, {id: 3, name: "H"}]
roles: ["Super", "Admin"]

3 个答案:

答案 0 :(得分:2)

这将在所有情况下呈现组件,除非 customers.items 只有一个元素并且角色包括 'Super'

const hasSingleCustomer = customers?.items?.length === 1
const hasSuperRole = roles.includes('Super'))


{!(hasSingleCustomer && hasSuperRole) && <Component />}

如果您愿意,也可以将其写为 {(!hasSingleCustomer || !hasSuperRole) && <Component />}

答案 1 :(得分:1)

你可以试试这个方法

{(customers.items.length > 1 && roles.includes("Super")) ? <If Success Component/> : <Failure Component>}

我已经按照你的要求写了,因为我正在检查角色数组中是否有“超级”,你仍然可以在括号()内操作操作,我们必须使用?和:为了确保条件有效,

快乐编码:)

答案 2 :(得分:1)

我的建议是将方程/条件拆分为更小的变量,然后使用它们来创建有效性条件。这样,您的代码更具可读性且更易于维护

const length = customers.items.length
const isSuperUser = roles.includes('Super')
const isAdminUser = roles.includes('Admin')
const isAllowedForSuper = isSuperUser && length === 1
const isAllowedForAdmin = isAdminUser && length === 0

if (isAllowedForSuper || isAllowedForAdmin) {
  return <Component {...props} />
}
return null