我总共有11张卡。每张卡都有其自己的删除按钮。我的目标是在按下删除按钮时将其从打印卡的json文件中删除。
卡被按下。没事我只是无法删除名为deletePer的函数中的数据。代码:
import React, { Component } from 'react'
import Wrap from "../../Wrap/Wrap";
import CardStyle from '../cardStyle/cardStyle';
import axios from "axios";
import Api from "../axios-get";
class CreateCard extends Component {
constructor(props){
super(props);
this.state = {
cards: []
};
this.readCards();
};
readCards = () => {
//verileri dizi yoluyla aktarmaya çalışıyorum
Api.get('/data.json').then(arr => {
// Object.values(arr.data).map( a => console.log(a) )
let a = Object.values(arr.data)
console.log(a[0].fullName)
Object.values(arr.data).map( val => this.setState({
cards: [
...this.state.cards,
{
fullName: val.fullName,
job: val.job
}
]
}))
this.state.cards = [];
}
)
}
clickEvent = () => {
var fullName = document.getElementById("fullName").value;
var job = document.getElementById("job").value;
var cards = [
...this.state.cards,
{
fullName: fullName,
job: job
}
];
var cardValue = {
fullName: fullName,
job: job
};
this.setState({cards: cards});
Api.post('/data.json',cardValue)
.then(response => console.log(response))
.catch(error => alert(error));
this.readCards();
}
deletePer = (personName) => {
// console.log(personName);
Api.get('/data.json').then(arr => {
Object.values(arr.data).map( val => {
if(personName === val.fullName){
console.log(val.fullName);
axios.delete("/data.json",{
data: {fullName: personName}
})
}else{
alert('Bir hata oluştu. Sayfayı yenileyiniz...')
}
})
})
// Api.get('/data.json', arr => {
// Object.values(arr.data).map(val => {
// if(personName === val.fullName){
// axios.delete('/data.json',
// {data:{username: personName}
// });
// }else{
// alert("sorun oluştu")
// }
// })
// })
};
render() {
return (
<Wrap>
<input type="text" id="fullName" />
<input type="text" id="job"/>
<button onClick={this.clickEvent}>ADD PERSON</button>
{/* <button onClick={this.readCards}>Verileri al</button> */}
{this.state.cards.map( (card, index) => (
<CardStyle
key = {index}
fullName = {card.fullName}
job = {card.job}
clicked = {() => this.deletePer(card.fullName)}
/>
))}
</Wrap>
)
}
}
export default CreateCard;
答案 0 :(得分:1)
我认为这是因为您没有指定任何ID,而是仅传递了{data {fullName: personName}}
。
应为:
Api.get('/data.json').then(arr => {
Object.values(arr.data).map( val => {
if(personName === val.fullName){
console.log(val.fullName);
axios.delete("/data.json",{
data: {id: itemId}
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
}else{
alert('Bir hata oluştu. Sayfayı yenileyiniz...')
}
})
})