【发布时间】:2020-03-12 07:17:00
【问题描述】:
我成功创建了多个过滤按钮。但是,我注意到,当我第一次单击一个过滤按钮显示居住在英国的学生时,列表显示过滤结果,然后我单击另一个过滤按钮显示居住在美国的学生,列表只是空白,我的控制台显示数组是空的。我不知道发生了什么。
import React, { Component } from 'react';
import profiles from '../data/berlin.json';
export class FaceBook extends Component {
constructor(props){
super(props);
this.state = {
profilelist: profiles,
filtered: profiles
}
}
showProfile = () =>{
return this.state.profilelist.map((eachProfile,i)=>{
let studentBoolean;
if(eachProfile.isStudent) {
studentBoolean = "Student";
} else {studentBoolean = "Teacher"}
return(
<div className="profilecard" key={i}>
<div className="profileimage"><img src={eachProfile.img} alt="Actor"/></div>
<div className="profilecontent">
<ul>
<li><strong>First Name:</strong> {eachProfile.firstName}</li>
<li><strong>Last Name:</strong> {eachProfile.lastName}</li>
<li><strong>Country:</strong> {eachProfile.country}</li>
<li><strong>Type:</strong> {studentBoolean}</li>
</ul>
</div>
</div>
)
})
}
showAll = () =>{
this.setState({
profilelist: profiles
})
}
showEngland = () =>{
this.setState({
profilelist: profiles,
filtered: profiles
})
let filterEngland = [...this.state.profilelist];
let newList = filterEngland.filter(item => {
const lc = item.country.toLowerCase();
const filter = "england";
return (lc === filter);
})
console.log(newList);
this.setState({
profilelist: newList,
filtered: newList
})
}
showUSA = () =>{
this.setState({
profilelist: profiles,
filtered: profiles
})
let filterUSA = [...this.state.profilelist];
let newusaList = filterUSA.filter(item => {
const lc = item.country.toLowerCase();
const filter = "usa";
return (lc === filter);
})
this.setState({
profilelist: newusaList,
filtered: newusaList
})
}
render() {
console.log(this.state.profilelist);
return (
<div>
<div className="menubar">
<button onClick={this.showAll}>All</button>
<button onClick={this.showEngland}>England</button>
<button onClick={this.showUSA}>USA</button>
</div>
<div className="profileTable">
{this.showProfile()}
</div>
</div>
)
}
}
export default FaceBook
如您所见,我创建了 3 个按钮“All”、“England”、“USA”。我还为每个按钮创建了 3 个函数。 all 按钮重置state.profilelist,而英国和美国显示过滤结果。我尝试添加
this.setState({
profilelist: profiles,
filtered: profiles
})
在英格兰和美国函数的开头,以便在过滤之前重置列表,但它不起作用....
【问题讨论】:
标签: javascript reactjs