将 firestore onSnapShot 与 React redux 结合使用的正确方法

Jak*_*kob 5 firebase react-native redux-thunk react-redux google-cloud-firestore

我试图找出将 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);
}
Run Code Online (Sandbox Code Playgroud)

};

这工作正常,正确的数据被发送到组件并显示。问题是,如果用户签入,签入数据应该调整,但事实并非如此,因为我只获取一次数据并发送它,并且状态不会重新渲染。

我的问题是我应该如何处理这个问题?我用.onSnapshot()代替吗.get().fetchCheckins()我是从动作创建者那里打电话吗.checkin()?我如何根据最佳实践进行处理?谢谢

Dan*_*rov 3

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

在你的情况下,如果你使用 .get() - 你会得到一次更新,如果任何数据发生变化,firestore 不会通知你。这就是为什么您看不到这些变化。

PS checkout redux-firestore:https://github.com/prescottprue/redux-firestore - 这是一个很好的库,可以帮助您进行 redux 绑定。