首页 > 解决方案 > Reactjs 和 axios。从 json 数据库中删除对象

问题描述

我有一个硬编码的 json 数据库。

文件 db.json

"persons": [

    {
      "name": "ss",
      "number": "ssssd",
      "id": 17
    },
    {
      "name": "ddd",
      "number": "6tyhhth",
      "id": 18
    },
    {
      "name": "almejas",
      "number": "1234",
      "id": 19
    },
    {
      "name": "pailo",
      "number": "244",
      "id": 20
    }
  ]
}

我想创建一个按钮来删除条目。该按钮已创建,但我无法通过按下它来删除条目。

我创建按钮:

文件:Person.js

import React from 'react'
//deleteContact props are also needed when adding the delete button
const Person = ({ person, deleteContact }) => {
   console.log("person.js props "+person.id)
   
    return (
      <li> 
        {person.name} {person.number}  
        <button onClick={deleteContact}>Delete {person.id} </button> 
      </li>
    )
  }

  export default Person

这里是我不知道如何实现删除功能的地方。

文件:app.js

import React, { useState, useEffect } from 'react'
import Person from './components/Person'
import Form from './components/Form'
import Filter from './components/Filter'

import FilterResults from './components/FilterResults'
import contactService from './services/persons'

//npm run server

const App = () => {




  //Reminder: current state, function that updates it, initial state.

  const [ newName, setNewName ] = useState('')
  const [ newNumber, setNewNumber ] = useState('')
  const [contacts, setContacts] = useState([])
  //Filter
  const [ filter, setFilter ] = useState('')
  
  
  //contactService is importer from /services/persons.
  //.getAll is like typing: axios.get('http://localhost:3001/persons')

  //Effect hooks used to fetch data from the server. The data fetched is saved
  //into the contacts state variable
  useEffect(() => {
    
    contactService
    .getAll()
    .then(response => {
      setContacts(response.data)
    console.log(contacts)
      
    
  })
  
  }, [])
/* 
  second parameter of useEffect is used to specify how often the effect
   is run. If the second parameter is an empty array [], 
   then the effect is only run along with the first render of 
   the component. */

  console.log('render', contacts.length, 'contacts')


  //adding new persons
  const addPerson = (event) => {
    event.preventDefault()
    /* complete the addPerson function for creating new persons */
    const personObject = {
      name: newName,
      number: newNumber,
      //The server will create the id 
      //id: persons.length + 1,
    }

    //Adding the data to the server
    /* 
    using separate server comunication module from persons.js
     "create" instead of previous code:
    axios
    .post('http://localhost:3001/persons', personObject) 
    
    replaced by:
    
    contactService
    .create(personObject)
    */

    contactService
    //Passing personObject to create
    .create(personObject)
    .then(response => {
      console.log(response)
         //After concat, the fiel is set to blank again ('').
//Updating state after creating, to display created contact.
    setContacts(contacts.concat(personObject))
    setNewName('')
    setNewNumber('')
    })

  
  }
 //Delete contacts
 const deleteContact = (id) => {
 
}


  const handlePersonChange = (event) => {
    console.log(event.target.value)
    setNewName(event.target.value)
  }
  const handleNumberChange = (event) => {
    console.log(event.target.value)
    setNewNumber(event.target.value)
  }

  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }
 
 
  const personsToShow = filter === ''
    ? contacts
    : contacts.filter(person =>
        person.name.toLowerCase().includes(filter.toLowerCase()))
  const row_names = () => personsToShow.map(person => 
    <p key={person.name}>{person.name} {person.number} </p>
  )

 

  return (
    <div>
 <Filter value={filter} onChange={handleFilterChange} />

      <Form
      onSubmit={addPerson}
      name={{value: newName, onChange: handlePersonChange}}
      number={{value: newNumber, onChange: handleNumberChange}}
      deleteContacts={() => deleteContact()}

      />
 <h2>Numbers from database</h2>
     
   {/*   The contents of the database are stored on the variable contacts.
     I map through the array. Person.js component used.  */}
      <ul>
      {contacts.map(person => 
      //Pass all the props from person to Person.js
          <Person 
          key={person.id} 
          person={person} 
          deleteContact={person.id}
         
          
          />
         
        )}
      </ul>
      <h2>Filter results</h2>
      <FilterResults persons={row_names()} />

    </div>
  )
}

export default App

我不明白如何做到这一点,但在上面的代码中你看到我试过这个:

 //Delete contacts
 const deleteContact = (id) => {
 
}

然后我尝试在return语句中将id传递给deleteContact

 <h2>Numbers from database</h2>
     
   {/*   The contents of the database are stored on the variable contacts.
     I map through the array. Person.js component used.  */}
      <ul>
      {contacts.map(person => 
      //Pass all the props from person to Person.js
          <Person 
          key={person.id} 
          person={person} 
          deleteContact={person.id}
         
          
          />
         
        )}
      </ul>

axios 逻辑位于单独的模块上。人.js

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

 const getAll = () => {
  return axios.get(baseUrl)
} 
//url to post, and what to post, in that case, the object posted is personobject
const create = personObject => {
  return axios.post(baseUrl, personObject)
}
const deleteContact = (id)=>{
  const request = axios.delete('{$baseUrl}/${id}')
  return request.then(response =>response.data)
  }
/* const update = (id, personObject) => {
  return axios.put(`${baseUrl}/${id}`, personObject)
} */

export default { 
  getAll: getAll,  
  create: create, 
  deleteContact: deleteContact,
  /* update: update  */
}

getAll 工作并创建。deleteContact,没有。

我不明白的是如何获取要删除的条目的 ID 并将其传递给 axios,以便从 db.json 中删除具有该 ID 的对象

标签: reactjsaxios

解决方案


在 Person.js 中,您可以通过使用回调获取 id 来删除

<button onClick={()=>deleteContact(person.id)}>Delete {person.id} </button>

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


const deleteContact = (id)=>{
  const request = axios.delete('{$baseUrl}/${id}')
  request.then(response =>response.data)
  }

const Person = ({ person, deleteContact }) => {
   console.log("person.js props "+person.id)
   
    return (
      <li> 
        {person.name} {person.number}  
        <button onClick={()=>deleteContact(person.id)}>Delete {person.id} </button> 
      </li>
    )
  }

  export default Person

推荐阅读