You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中通过函数实现输入框按角色禁用的异常问题

解决React组件中角色校验函数返回Promise导致disabled属性失效的问题

问题核心

你编写的checkRole是异步函数(带有async关键字),调用后会直接返回Promise对象,而React组件的disabled属性需要的是布尔值,因此才会出现始终拿到Promise<Pending>的问题。另外你在函数里用await包裹forEach属于冗余操作——forEach是同步遍历方法,不会返回Promise,await对它完全不起作用。

修复方案

1. 重构checkRole函数(移除异步逻辑)

角色校验是纯同步操作(仅遍历本地用户对象),不需要async/await,直接改成同步函数,同时用更简洁的逻辑实现校验:

/**
 * @description 检查用户是否拥有数组中的任意角色
 * @param {Object} user - 当前登录用户对象
 * @param {Array} roles - 需要校验的角色数组
 * @returns {Boolean} 拥有任一角色返回true,否则返回false
 * @example checkRole({user}, ['isAdmin'])
 * @example checkRole({user}, ['isAdmin', 'isPartner'])
 *
 * @author   Austin Howard
 * @version  1.0.1
 * @since    1.0.0
 */
export default (user, roles) => {
  if (!user) return false;
  // 使用some方法:只要找到一个匹配且值为true的角色就返回true
  return Object.keys(user).some(key => roles.includes(key) && user[key]);
};

2. 组件中正确调用修改后的函数

现在checkRole直接返回布尔值,可直接传给disabled属性(注意你原代码里缺失了一个闭合括号,需要补上):

<Form.Group className={styles.boolean} controlId="isPaid">
  {/* True/False */}
  <Form.Check
    type="switch"
    id="custom-switch"
    label="Is Paid User"
    checked={formData.isPaidUser}
    onChange={(e) =>
      setFormData({
        ...formData,
        isPaidUser: !formData.isPaidUser,
      })
    }
    // 修复:使用同步的checkRole,补上缺失的括号
    disabled={!checkRole(loggedInUser, ['isAdmin', 'isAccountant'])}
  ></Form.Check>
</Form.Group>

可选优化:用useMemo缓存校验结果

如果loggedInUser或角色数组会频繁变化,可使用useMemo缓存校验结果,避免每次渲染重复遍历:

import { useMemo } from 'react';

// 组件内部定义缓存逻辑
const hasPermission = useMemo(() => {
  return checkRole(loggedInUser, ['isAdmin', 'isAccountant']);
}, [loggedInUser]);

// 组件中使用缓存后的结果
disabled={!hasPermission}

内容的提问来源于stack exchange,提问作者Austin Howard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:20:37