reactjs - 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 的对象
解决方案
在 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
推荐阅读
- java - Spring Boot 2.4.5 和 Java 11 的模块系统问题
- youtube - 有没有办法通过另一个帐户进行 youtube 直播
- nginx - Nginx 中的反向代理和负载均衡器有什么区别?
- google-apps-script - Google 表格防止在 AppsScript 运行时更改公式目标
- javascript - 需要帮助显示范围滑块的值
- google-bigquery - Big Query 嵌套和重复数据
- c# - 使用 LINQ 比较两个列表,并使用一个或另一个的结果生成第三个列表
- javascript - 我在哪里存储刷新令牌和访问令牌以及如何使用它?
- django - Django:在表单字段前添加 $ 的简单解决方案
- python - Python REPL 字典