我有两个组件Display.jsx和DisplayList.jsx。组件协同工作以显示本地存储中的值。问题出在DisplayList.JSX handleDelete()方法循环上。
我不明白为什么它会删除第一个元素而不是所选元素?以及如何解决?
Display.jsx
import {DisplayList} from './DisplayList';
class Display extends Component {
constructor(props){
let data = JSON.parse(localStorage.getItem('data'));
super(props)
this.state = {
data: data,
}
// Methods
this.displayValues = this.displayValues.bind(this);
}
displayValues(){
return this.state.data.map((data1, index) =>
<DisplayList
key = {index}
email = {data1.email}
password = {data1.password}
updateList = {this.updateList}
/>
)
}
// This is the method that will be called from the child component.
updateList = (data) => {
this.setState({
data
});
}
render() {
return (
<ul className="list-group">
{this.displayValues()}
</ul>
)
}
}
export default Display;
DisplayList.jsx
import React, { Component } from 'react'
import {Button, Modal, Form} from 'react-bootstrap';
export class DisplayList extends Component {
constructor(props){
super(props)
this.state = {
email: '',
password: '',
show: false,
};
// Methods
this.handleDelete = this.handleDelete.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange(event){
this.setState({
[event.target.name]: event.target.value
})
};
handleDelete(){
const data = JSON.parse(localStorage.getItem('data'));
for (let index = 0; index < data.length; index++) {
if(this.props.email === data[index].email &&
this.props.password === data[index].password){
console.log(this.props.email);
console.log(data[index]);
data.splice(data[index], 1);
}
console.log('loop count');
}
localStorage.setItem('data', JSON.stringify(data));
this.props.updateList(data);
}
render() {
return (
<div className = "mt-4">
<li className="list-group-item text-justify">
Email: {this.props.email}
<br />
Password: {this.props.password}
<br />
<Button onClick = {this.handleShow} variant = "info mr-4 mt-1">Edit</Button>
<Button onClick = {this.handleDelete} variant = "danger mt-1">Delete</Button>
</li>
</div>
)
}
}
答案 0 :(得分:1)
代替:
data.splice(data[index], 1);
尝试重写整个数组:
data = [
...data.slice(0, index),
...data.slice(index + 1)
];
答案 1 :(得分:0)
handleDelete(){
const data = JSON.parse(localStorage.getItem('data'));
const filteredData = data.filter(
x => !(x.email === this.props.email && x.password === this.props.password)
);
localStorage.setItem('data', JSON.stringify(filteredData));
this.props.updateList(filteredData);
}