因此,在我的项目中,我使用react作为前端,django作为后端.我有以下模型

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

我创建了下面的视图,以获取我定义的角色 Select 到前端,

@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'),

现在,在我的前端,我有一个表单,其中一个字段是角色,当点击时,应该显示一个填充有角色 Select 的列表(只在这里粘贴所需的代码),

<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>
      </form>
    </div>

但是我没有看到网页上的角色选项,

enter image description here

I have logged the response I get when calling the endpoint and I see the role options being fetchedenter image description here

下面的代码显示了我如何在网页上设置角色选项

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

  useEffect(() => {
    // Fetch role options from backend when component mounts
    axios.get('http://127.0.0.1:8000/roles/')
    .then(response => {
      // Check if response data is an array
      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);
    });
}, []);

我不知道为什么我不能看到网页上的角色 Select ,即使在我从端点得到正确的回应后,

推荐答案

因为没有idrole,所以你只返回了一个字符串列表.你应该把这些放在字典里,比如:

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

然而,它并没有真正的"id",或者至少它不是一个模型的id.


Note:2008年,Phil Haack discovered a way to obtain data from the outer JSON array. 虽然大多数浏览器已经实现了对策,但最好还是使用 JSON对象作为数据的"信封".这就是为什么一个 JsonResponse [Django-doc] 默认情况下,不允许dict以外的东西作为外部对象.它可能 因此,最好将数据包装在字典中并将safe=True保持在True上.

Reactjs相关问答推荐

如何使用mui为可重复使用的react 按钮应用不同的风格

无法使用#13;或br将新行设置为文本区域'"&"<>

使用useReducer时,props 未从父级传递给子或孙级

后端关闭时如何在REACTION AXIOS拦截器中模拟数据?

如何在重新图表中更改悬停时的条形填充 colored颜色 ?

UseEffect和useSelector的奇怪问题导致无限循环

使用REACT-RUTER-V6和ZUSTANDreact 中的身份验证

react -无法获取函数的最新参数值

useEffect不重新渲染

React useEffect 问题...异步函数内的变量正在获取延迟的更新值

如何获取用户在 GooglePlacesAutocomplete 中输入的文本?

如何删除 bootstrap 手风琴上的边框

在 React 中是否有任何理由要记住 Redux 操作创建者?

react :输入失go 焦点,输入一个字符,

如何修改 react/jsx-no-useless-fragment 规则以允许 <>{children}

从服务器获取数据时未定义,错误非法调用

Cypress 组件测试不渲染react 组件(但它的内容)

AWS 全栈应用程序部署教程构建失败

如何检索包含动态段的未解析路径?

如何使用 cypress 获取 MUI TextField 的输入值?