我有两个组件:Display和DisplayList。这两个组件一起工作以从本地存储中显示值。所有都能正常工作,但是当我激活handleDelete方法时,本地存储中的值被删除,但React并未重新呈现列表。
总结:我希望在激活handleDelete()方法后,React能够重新呈现我的displayValues。 Github 链接
总结:我希望在激活handleDelete()方法后,React能够重新呈现我的displayValues。 Github 链接
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}
/>
)
}
render() {
return (
<ul className="list-group">
{this.displayValues()}
</ul>
)
}
}
DisplayList.JSX
import {Button} from 'react-bootstrap';
export class DisplayList extends Component {
constructor(props){
super(props)
// Methods
this.handleDelete = this.handleDelete.bind(this);
}
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){
data.splice(data[index], 1);
}
}
localStorage.setItem('data', JSON.stringify(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 variant = "info mr-4 mt-1">Edit</Button>
<Button onClick = {this.handleDelete} variant = "danger mt-1">Delete</Button>
</li>
</div>
)
}
}
localStorage
中删除时,也要从Display
的状态中删除该项。 - Agney