我正在使用React-JS制作一个列表。我正在努力使用条件运算符对数据进行排序。
我添加了条件运算符但它没有用。带'string'的条件运算符可以在React中使用吗?
style={{ display : this.state.male && friend.gender == "male" ? "block" : "none" }}
List.js
class FriendList extends Component {
constructor(props, context) {
super(props, context);
this.state = {
male: false,
female: false
}
}
maleButton(e) {
this.setState({
male: !this.state.male
});
}
femaleButton(e) {
this.setState({
female: !this.state.female
});
}
render() {
return (
<div>
<button onClick={this.maleButton.bind(this)}>Male</button>
<button onClick={this.femaleButton.bind(this)}>Female</button>
<ul className={styles.friendList}>
{
this.props.friends.map((friend, index) => {
return (
<FriendListItem
key={index}
id={index}
name={friend.name}
starred={friend.starred}
gender={friend.gender}
style={{ display : this.state.male && friend.gender == "male" ? "block" : "none" }}
{...this.props.actions} />
);
})
}
</ul>
</div>
);
}
}
FriendList.propTypes = {
friends: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
export default FriendList;
数据将如下:
const initialState = {
friendsById: [{
name: 'Theodore Roosevelt',
starred: true,
gender: 'male'
}, {
name: 'Abraham Lincoln',
starred: false,
gender: 'male'
}, {
name: 'George Washington',
starred: false,
gender: 'male'
}, {
name: 'Hillary Clinton',
starred: false,
gender: 'female'
}]
};
答案 0 :(得分:2)
可能会稍微改变一下你的方法,然后先filter结果:
this.props.friends
.filter(friend =>
this.state.male && friend.gender === 'male' ||
this.state.female && friend.gender === 'female'
)
.map((friend, index) => ...)
除非你需要同时显示male
和female
性别,否则我给你的另一个建议就是删除 duplication 本身(同时包含两个布尔值)例如,将一个性别值存储为字符串。有了这个,过滤方法变得更容易理解:
this.props.friends
.filter(friend => friend.gender === this.state.gender)
.map((friend, index) => ...)
答案 1 :(得分:0)
您可以使用.filter
代替.map
而不是{
this.props.friends.filter((friend, index) => {
if((this.state.male && friend.male) || (this.state.female && friend.female)) {
return (
<FriendListItem
key={index}
id={index}
name={friend.name}
starred={friend.starred}
gender={friend.gender}
style={{ display : "block" }}
{...this.props.actions} />
);
}
})
}
。为此您可以这样做:
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
for (DocumentSnapshot snapshot : snapshots) {
System.out.println(snapshot.getId());
// This prints document IDs of documents that were deleted
// from the collection when the app was not running
}
}
});