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

React项目中Axios调用Swagger API时Delete请求ID传值为undefined及列表key警告问题求助

解决你的DELETE请求失败和React Key警告问题

我来帮你逐一解决这两个问题:

一、PUT/DELETE请求失败(重点解决DELETE问题)

从控制台错误DELETE https://localhost:44373/api/Users/undefined 400可以看出,你传递给DELETE接口的userId是undefined,导致接口无法识别请求。

问题原因:

在你调用onDelete的时候,传入的是data.id,但从你的setData函数和API返回的数据结构来看,用户的ID字段是userId而不是id,字段名不匹配导致获取不到正确的ID值。

解决步骤:

  1. 修改删除按钮的onClick事件,把data.id改成data.userId:
<button className="table-btn" onClick={() => onDelete(data.userId)}>Delete</button>
  1. 给DELETE请求添加错误捕获,避免未捕获的Promise错误:
const onDelete = (userId) => {
  axios.delete(`https://localhost:44373/api/Users/${userId}`)
    .then(() => { getData(); })
    .catch(error => {
      console.error("删除用户失败:", error);
      // 这里可以添加用户友好的错误提示,比如弹窗
    });
}

至于PUT请求的问题,大概率也是类似的字段名不匹配或者参数传递错误,你可以参照这个思路检查PUT接口的参数是否正确传递了userId。

二、"Each child in a list should have a unique key"警告

你给表头的<th>加了key,但警告的来源是你通过map生成的表格行(<tr>)没有添加唯一的key属性。React要求列表渲染的每个子元素必须有唯一的key,用来帮助React识别元素的变化。

解决步骤:

  1. 在map返回的<tr>上添加key属性,使用唯一的userId作为key值:
{APIData.map((data) => {
  return (
    <tr key={data.userId}> {/* 这里添加key */}
      <td>{data.firstName}</td>
      <td>{data.lastName}</td>
      <td>{data.emailAddress}</td>
      <td>{data.phoneNumber}</td>
      {/* 修正下面的Link嵌套结构 */}
      <td>
        <Link to='/UpdateUser'>
          <button className="table-btn" onClick={() => setData(data)}>Update</button>
        </Link>
      </td>
      <td>
        <button className="table-btn" onClick={() => onDelete(data.userId)}>Delete</button>
      </td>
    </tr>
  )
})}
  1. 顺便修正你Update按钮的DOM结构错误:原来的代码里<Link>直接包裹了<td>,这不符合HTML规范,会导致渲染异常,应该把<Link>放在<td>内部。

修正后的完整Read组件代码片段

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Table } from 'react-bootstrap';
import { Link } from 'react-router-dom';

export default function Read() {
  const setData = (data) => {
    let { userId, firstName, lastName, emailAddress, phoneNumber, password } = data;
    localStorage.setItem('UserId', userId);
    localStorage.setItem('First Name', firstName);
    localStorage.setItem('Last Name', lastName);
    localStorage.setItem('EmailAddress', emailAddress);
    localStorage.setItem('Phonenumber', phoneNumber);
    localStorage.setItem('Password', password)
  }

  const url = `https://localhost:44373/api/Users`;

  const getData = () => {
    axios.get(url)
      .then((getData) => {
        setAPIData(getData.data);
      })
  }

  const onDelete = (userId) => {
    axios.delete(`https://localhost:44373/api/Users/${userId}`)
      .then(() => { getData(); })
      .catch(error => console.error("删除失败:", error));
  }

  const [APIData, setAPIData] = useState([]);

  useEffect(() => {
    axios.get(`https://localhost:44373/api/Users`)
      .then((response) => {
        setAPIData(response.data);
      })
      .catch(error => console.error("获取数据失败:", error));
  }, [])

  return (
    <div>
      <Table bordered>
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Emailaddress</th>
            <th>Phonenumber</th>
            <th>Update</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {APIData.map((data) => {
            return (
              <tr key={data.userId}>
                <td>{data.firstName}</td>
                <td>{data.lastName}</td>
                <td>{data.emailAddress}</td>
                <td>{data.phoneNumber}</td>
                <td>
                  <Link to='/UpdateUser'>
                    <button className="table-btn" onClick={() => setData(data)}>Update</button>
                  </Link>
                </td>
                <td>
                  <button className="table-btn" onClick={() => onDelete(data.userId)}>Delete</button>
                </td>
              </tr>
            )
          })}
        </tbody>
      </Table>
    </div>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 10:09:07