firebase - 将 firestore onSnapShot 与 react redux 一起使用的正确方法

标签 firebase react-native react-redux google-cloud-firestore redux-thunk

我正在尝试找出将 firestore.onSnapshot 与 react-redux 一起使用的正确方法。

我目前在我的操作文件中有这段代码,我在我的组件中调用 componentWillMount()

export const fetchCheckins = () => async (dispatch) => {
const {currentUser} = firebaseService.auth();
try {
    let timestamp = (new Date());

    //set timestamp for beginning of today
    timestamp.setHours(0);
    //get checkins today
    let checkinstoday = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data());
    //set timestamp for beggining of week
    timestamp.setDate(-(timestamp.getDay()));
    //get checkins (week)
    let checkinsweek = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data());
    //set timestamp for begging of month
    timestamp.setDate(0);
    //get checkins (month)
    let checkinsmonth = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data()); 

    dispatch({type: FETCH_CHECKINS, payload: { today: checkinstoday, week: checkinsweek, month: checkinsmonth}});
}
catch(e){
  console.error(e);
}

};

这工作正常,正确的数据被发送到组件并显示。问题是,如果用户 checkin , checkin 数据应该调整,但实际上并没有,因为我只获取一次数据并发送它,并且状态没有重新呈现。

我的问题是我应该如何处理这个问题?我是否使用 .onSnapshot() 而不是 .get()?我是否从 .checkin() 操作创建者调用 .fetchCheckins()?我如何根据最佳实践进行处理?谢谢

最佳答案

根据 firestore 的文档,如果您需要实时更新,您应该使用 onSnapshot: https://firebase.google.com/docs/firestore/query-data/listen

在您的情况下,如果您使用 .get() - 您将获得一次更新,并且如果任何数据发生更改,firestore 将不会通知您。这就是您没有看到更改的原因。

附言结帐 redux-firestore:https://github.com/prescottprue/redux-firestore - 这是一个很好的库,可以帮助您进行 redux 绑定(bind)。

关于firebase - 将 firestore onSnapShot 与 react redux 一起使用的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733377/

相关文章:

JavaScript - React Native 等待回调执行并使用其变量

reactjs - 用 Jest 测试中继 [createFragmentContainer]?

java - Firebase Android getValue(class) 不起作用

firebase - 甚至没有运行应用程序,Firestore 数据库读取就在增加

javascript - 同时按日期和时间对数组进行排序?

javascript - React Redux 异步 Action 测试

javascript - 当状态更新时没有从 redux store 获取更新的状态

java - 如何从 Firebase 存储获取 URL getDownloadURL

react-native - 如何让 FlatList 填充高度?

javascript - 防止 react-redux 在状态改变时重新渲染整个页面