您可以执行以下操作:
constructor(props) {
super(props)
this.state={
providerId: '',
providerName: '',
providerService: '',
fav: false
}
this.ref = firebase.database().ref(`favorites/${firebase.auth().currentUser.uid}`);
}
componentDidMount() {
this._onFavourite = this.ref.on('child_added', () => {
this.setState({
fav: true
}, alert("Added To Favorite List"))
})
this._onUnFavourite = this.ref.on('child_removed', () => {
this.setState({
fav: false
}, alert("Removed from Favorite List"))
})
}
componentWillUnmount() {
if (this._onFavourite) {
this.ref.off('child_added', this._onFavourite);
}
if (this._onUnFavourite) {
this.ref.off('child_removed', this._onUnFavourite);
}
}
_favOrUnFav = () => {
if (!this.state.fav){
const {
providerId,
providerName,
providerService
} = this.state;
this.ref.set({
providerId,
providerName,
providerService
})
} else ref.set(null) OR you can use ref.remove()
}
const {
fav
} = this.state
<Icon
name={`ios-heart${fav ? "" : "-empty"}`}
style={{ backgroundColor: "red" }}
size={30}
color="#fff"
onPress={this._favOrUnFav}
/>
我希望它对你有帮助。