我正在使用Tinder这样的应用程序来练习我的React本地技能。我在从Firebase后端制作有条件渲染方面遇到了麻烦。
以下是我的代码。
class CardsScreen extends Component {
constructor(props) {
super(props);
this.state = {
users: [
{ name: "chris", gender: "male", interestedIn: "women" },
{ name: "jane", gender: "female", interestedIn: "men" },
{ name: "fred", gender: "male", interestedIn: "women" },
{ name: "vanessa", gender: "female", interestedIn: "men" }
],
data: {}
};
this.usersRef = firebase
.database()
.ref("users/" + this.props.currentUser.uid);
this.likedRef = firebase
.database()
.ref("users/" + this.props.currentUser.uid + "/likes");
}
componentDidMount() {
this.listenUserInterest();
}
listenUserInterest = () => {
this.usersRef.on("value", snapshot => {
let gender = snapshot.val().gender;
this.setState({ currentGender: gender });
console.log(gender);
});
};
handleYup = card => {
const user = this.props.currentUser.uid;
if (user) {
const newItem = {
name: card.name,
gender: card.gender,
interestedIn: card.interestedIn
};
this.likedRef.push().update(newItem);
}
console.log(`Yup for ${card.name}`);
};
handleNope(card) {
console.log(`Nope for ${card.text}`);
}
renderNoMoreCards() {
return (
<View>
<Text style={styles.noMoreCardsText}>No more cards</Text>
</View>
);
}
render() {
return (
<SwipeCards
cards={this.state.users}
renderCard={cardData => <User {...cardData} />}
renderNoMoreCards={this.renderNoMoreCards}
handleYup={this.handleYup}
handleNope={this.handleNope}
hasMaybeAction
source={{ uri: this.state.image }}
/>
);
}
}
function mapStateToProps(state) {
return {
currentUser: state.user.currentUser
};
}
到目前为止,我根据兴趣进行了注册,一切顺利。我将一些静态数据根据其性别渲染。这是我卡住的部分。我只是不知道如何获取数据并根据Firebase的性别进行有条件的渲染。如果我对女性感兴趣,我只想渲染女性卡片。该方法应该是什么?我尝试使用异步等待,但无法使其起作用。
当您将数据分配给滑动卡时,仅在此处过滤数据。
这样,
<SwipeCards
cards={this.state.users.filter(item=>item.gender == this.state.currentGender)} //this.state.currentGender contains current gender which can be any variable not necessary to be state
renderCard={cardData => <User {...cardData} />}
renderNoMoreCards={this.renderNoMoreCards}
handleYup={this.handleYup}
handleNope={this.handleNope}
hasMaybeAction
source={{ uri: this.state.image }}
/>
将当前性别存储在状态或变量
对于条件渲染,您可以在渲染方法中使用类似的内容:{this.state.gender =='f'?[//view]:[//view]}但是我想在您的情况下,您需要首先,将列表分开,然后显示列表,这是更好的方法,而不是条件渲染
,但我只能通过此功能从firebase获取数据。如果我将性别而不是感兴趣,它将给我性别。但是我该如何将其放在状态或变量中。它仅在功能中可用?
listenUserInterest = card => {
this.usersRef.on("value", snapshot => {
let interestedIn = snapshot.val().interestedIn;
this.setState({ data: interestedIn });
console.log(interestedIn)// this gives interested in data
});
};