我实时从firebase / fire store收到消息。但我希望通过将动态数字(日期)传递给Firestore中的where子句并在数据的数量(日期)大于给定的动态数字时获取数据来动态查询数据。我从redux商店获取动态数据并通过道具将其传递到where。但问题是号码没有更新。我在构造函数中定义了Firestore的东西。我在下面附上了我的代码。我的目标是,如果数据的日期大于给定日期,则从Firestore获取数据。
我已经尝试了很多方法,并发现当我从后端发送消息时,由redux传递的动态日期不会更新bcoz我在构造函数中使用该props值。
...
import firebase from 'react-native-firebase'
import {addLastSeen} from '../Redux/Actions'
import {addMessage} from '../Redux/Actions'
import {connect} from 'react-redux'
firebase.initializeApp({
apiKey: 'AIzaSyDA8acz_UcdHK1QaIPd6sG1Cp5bma_gTvg',
projectId: 'notifaapp'
})
const firestore = firebase.firestore()
class Navigate extends React.Component{
constructor(props) {
super(props);
this.ref = firestore.collection('messages')
.orderBy('date', 'desc')
.where("date",'>' ,this.props.lastSeen)
// date is something like this 1555520642840
// this.props.lastSeen is getting from redux store via props
this.unsubscribe = null;
}
componentDidMount() {
this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate)
}
componentWillUnmount() {
this.unsubscribe();
}
onCollectionUpdate = (querySnapshot) => {
const todos = [];
querySnapshot.forEach((doc) => {
const { title, complete, message, date } = doc.data();
this.props.addLastSeen(date) // dispatching an action and update redux store
todos.push({
key: doc.id,
title,
message,
date : new Date(date)
});
});
alert(JSON.stringify(todos))
todos.map(value => {
message = {
"key": value.key,
"title": value.title,
"body": value.message,
"date": value.date,
"read":"false",
"archived":"false"
}
this.props.add(message)
})
}
render(){
return(
...
)
}
}
function mapStateToProps(state){
return {
lastSeen : state.lastSeen.date,// getting date from redux store
}
}
export default connect(mapStateToProps, {add:addMessage, addLastSeen:addLastSeen})(Navigate)
如果不创建新查询并重新订阅,则无法更改onSnapshot查询。
您可以利用componentDidUpdate lifecycle call并检查lastseen酒店的变化。
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.lastSeen !== prevProps.lastSeen) {
// un-subscribe and re-subsricbe with modified query
}
}
虽然这可以解决您的问题,但我认为它会导致大量订阅操作和重新渲染