首页 > 解决方案 > 删除 http://localhost:3000/people/[object%20Object] 404(未找到)

问题描述

所以我一直试图用这个函数从我的表中删除一个人:

  const deletePerson = async (id) => {
    await fetch(`http://localhost:3000/people/${id}`, {
      method: "DELETE",
      headers: {
        "Content-type": "application/json"
      }
    })

    await setPeople(people.filter(person => person.id !== id))
  }

这是表格:

<table>
    <thead>
       <tr>
         <th>#</th>
         <th>Name</th>
         <th>Age</th>
         <th></th>
       </tr>
   </thead>
    <tbody>
       {people.map((person) => (
          <tr key={person.id + 1}>
            <td>{person.id}</td>
            <td>{person.name}</td>
            <td>{person.age}</td>
            <td>
              <button onClick={deletePerson} id="remove-button">REMOVE</button>
            </td>
         </tr>
       ))}
    </tbody>
</table>

这是json文件(我使用mock db,JSON服务器):

{
  "people": [
    {
      "name": "John Doe",
      "age": "69",
      "id": 1
    },
    {
      "name": "Jane Doe",
      "age": "64",
      "id": 2
    }
  ]
}

当我单击删除按钮时,删除功能无法识别 id(我猜)并且出现此错误。我一直在尝试自己解决它,但我无法成功。我是 ajax 和 http 请求的新手,所以我愿意接受建议和信息。

标签: javascriptreactjsajaxhttp-delete

解决方案


您正在传递整个person对象,而您只需要 ID。要么只传递 ID,要么修改你的deletePerson来处理person对象:

  const deletePerson = async (person) => {
    await fetch(`http://localhost:3000/people/${person.id}`, {
      method: "DELETE",
      headers: {
        "Content-type": "application/json"
      }
    })
    await setPeople(people.filter(_person => _person.id !== person.id))
  }

推荐阅读