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

React前端下拉列表无法显示Django后端返回的角色选项

问题:React下拉列表无法渲染后端返回的角色选项

技术栈

  • 前端:React + Axios
  • 后端:Django

相关代码

Django 后端

Role 模型

class Role(models.Model):
    ROLE_CHOICES = (
        ('Recruiter', 'Recruiter'),
        ('Manager', 'Manager'),
        ('Business Development Partner', 'Business Development Partner'),
        ('Business Development Partner Manager', 'Business Development Partner Manager'),
        ('Account Manager', 'Account Manager'),
    )
    role = models.CharField(max_length=50, choices=ROLE_CHOICES)

    def __str__(self):
        return self.name  # 注:模型无name字段,建议改为return self.role

视图函数

@csrf_exempt
def role_choices(request):
    roles = [role[1] for role in Role.ROLE_CHOICES]
    return JsonResponse(roles, safe=False)

路由配置

path('roles/', role_choices, name='roles_list'),

React 前端

数据获取逻辑

const [roleOptions, setRoleOptions] = useState([]);

useEffect(() => {
  axios.get('http://127.0.0.1:8000/roles/')
  .then(response => {
    if (Array.isArray(response.data)) {
      setRoleOptions(response.data);
      console.log(response.data);
    } else {
      console.error('Invalid response data:', response.data);
    }
  })
  .catch(error => {
    console.error('Error fetching roles:', error);
  });
}, []);

下拉列表渲染代码

<h2>Role</h2>
<label>
  Select Role:
  <select
    name="role"
    value={userData.role}
    onChange={handleInputChange}
  >
    <option value="">Select</option>
    {roleOptions.map(role => (
      <option key={role.id} value={role.role}>
        {role.role}
      </option>
    ))}
  </select>
</label>
<br />
<button type="submit" class="btn btn-default btn-sm">Submit</button>

问题分析

后端接口返回的是纯字符串数组(例如 ["Recruiter", "Manager", ...]),但前端渲染下拉选项时,错误地尝试访问每个数组元素的role.id和role.role属性——字符串类型根本没有这些属性,导致生成的<option>标签内容为空,自然在页面上看不到角色选项。

解决方案

方案1:修改前端渲染逻辑(推荐,无需改动后端)

直接使用数组中的字符串值作为选项的key、value和显示文本:

{roleOptions.map(role => (
  <option key={role} value={role}>
    {role}
  </option>
))}

方案2:修改后端返回格式(适配现有前端渲染逻辑)

如果不想改动前端代码,可以调整Django视图,返回包含id和role字段的对象数组:

@csrf_exempt
def role_choices(request):
    roles = [{"id": idx, "role": role[1]} for idx, role in enumerate(Role.ROLE_CHOICES)]
    return JsonResponse(roles, safe=False)

验证建议

打开浏览器控制台(F12),检查是否有Cannot read properties of undefined (reading 'id')这类错误,这能直接验证属性访问失败的问题。修改后刷新页面,下拉列表就能正常显示角色选项了。

内容的提问来源于stack exchange,提问作者Revanth Kumar Perla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:35:14