Axios删除方法出现错误404(未找到)

pbossiut  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(192)

我正在尝试在我的React应用程序中使用删除按钮。我将axios代码分离到一个单独的模块persons.js中,以使App.js中的代码更简洁。下面是删除函数逻辑,它在代码中的使用位置,一个提取的persons.js文件,以及Person组件。
我的代码在浏览器中运行良好,但当我单击删除按钮时,我不断收到错误消息“DELETE http://localhost:3001/persons/undefined 404(Not Found)”。我发现id存在无法识别的问题,但我已经将其包含在deletePerson函数的persons.js中。我还已经将key={person.id}包含在Person组件中。
<Person key={person.id} person={person} deleteButton={()=>handleDelete(index)} text='Delete' />
我也试过将上面Person组件中的索引更改为{person.id},但仍然不起作用。我该如何解决这个问题?

import { useState, useEffect } from 'react'
import personService from './services/persons'
import Person from './components/Person'

.......

const handleDelete = (index) => {
    const newPerson = persons.filter((_, id) => id !== index)

    personService
      .delete()
      .then(response=> {
        setPersons(newPerson.concat(response.data))
    })
  }

在这里,它用于Person组件

<ul>
  {persons.filter((person) => {
    if (searchTerm === "") {
    return person
  } else if (person.name.toLowerCase().includes(searchTerm.toLowerCase())) {
    return person
  }
  }).map((person, index) => {
    return (
    <Person key={person.id} person={person}  deleteButton={()=>handleDelete(index)} text='Delete' />
  );
  })
  }
  </ul>

上面使用的人员组件

import React from "react";

const Person = ({person, deleteButton, text}) => {
  return (
    <div>
        <li> 
          {person.name} {person.number}
          <button onClick={deleteButton}> {text} </button> 
        </li>
    </div>
  );
}

export default Person

persons.js

import axios from 'axios'
const baseUrl = 'http://localhost:3001/persons'

const getAll = () => {
  return axios.get(baseUrl)
}

const create = newObject => {
  return axios.post(baseUrl, newObject)
}

const update = (id, newObject) => {
  return axios.put(`${baseUrl}/${id}`, newObject)
}

const deletePerson = (id) => {
  return axios.delete(`${baseUrl}/${id}`)
}

export default { 
  getAll: getAll, 
  create: create, 
  update: update,
  delete: deletePerson
}
daolsyd0

daolsyd01#

在人员组件中更改函数调用

<Person key={person.id} person={person}  deleteButton={()=>handleDelete(person.id)} text='Delete' />

现在我们在handleDelete函数中传递person.id,因此我们需要如下所示更改函数

const handleDelete = (id) => {
const newPerson = persons.filter((person) => person.id !== id)

personService
  .delete(id)
  .then(response=> {
    setPersons(newPerson.concat(response.data))
})
}

相关问题