React-Redux-Firestore:页面不会在Firestore数据发生更改时自动重新加载

时间:2018-11-23 15:26:14

标签: reactjs redux google-cloud-firestore listener react-redux-firebase

我正在制作一个使用firestore数据库进行存储的react / redux应用程序,并且能够将我的应用程序链接到firestore,以便可以在我的应用程序中创建,读取,更新和销毁新数据到firestore 。问题是,在我的其中一个页面上,当我更新数据时,它会立即更新后端Firestore数据库中的数据,但是该更改不会立即反映在页面上的屏幕上。相反,它仅在我硬刷新页面后才会显示。另外,我目前在我的react / redux应用程序中使用https://github.com/prescottprue/react-redux-firebasehttps://github.com/prescottprue/redux-firestore处理firebase。

因此,我需要做些什么来使页面自动加载新更改,就像我以为使用react-firestore的“ firestoreConnect”会起作用,但事实并非如此。谢谢大家,这是我的代码:

数据组件

import React, { Component } from "react";
import { connect } from "react-redux";
import { firestoreConnect, isLoaded } from "react-redux-firebase";
import { compose } from "redux";
import { Grid } from "semantic-ui-react";
import BudgetHeader from "../BudgetHeader/BudgetHeader";
import BudgetList from "../BudgetList/BudgetList";
import BudgetNav from "../BudgetNav/BudgetNav";
import { updateBudgetData, compareChooser } from "../budgetActions";
import LoadingComponent from "../../../app/layout/LoadingComponent";

const mapState = state => ({
  users: state.firestore.ordered.users
});

const actions = {
  updateBudgetData,
  compareChooser
};

class BudgetDashboard extends Component {
  updateBudgetData = (newData, fieldToUpdate) => {
    this.props.updateBudgetData(newData, fieldToUpdate);
  };

  onCompareChange = (event, data) => {
    if (data.checked) {
      this.props.compareChooser("net");
    } else {
      this.props.compareChooser("gross");
    }
  };

  render() {
    const { users } = this.props;
    if (!isLoaded(users)) return <LoadingComponent inverted={true} />;
    return (
      <Grid>
        <Grid.Column width={16}>
          <BudgetNav />
          <BudgetHeader
            general={users[0].budget[1]}
            onCompareChange={this.onCompareChange}
          />
          <BudgetList
            className="standardSeparation"
            data={users[0].budget[0]}
            unallocatedBudget={users[0].budget[1].unallocatedBudget}
            unallocatedSpending={users[0].budget[1].unallocatedSpent}
            updateData={this.updateBudgetData}
          />
        </Grid.Column>
      </Grid>
    );
  }
}

export default compose(
  connect(
    mapState,
    actions
  ),
  firestoreConnect([
    {
      collection: "users",
      doc: "asdfasdfF21871d",
      subcollections: [{ collection: "budget" }]
    }
  ])
)(BudgetDashboard);

组件操作(其中包含更新预算方法)

export const updateBudgetData = (inputData, fieldToUpdate) => {
  return async (dispatch, getState, { getFirebase, getFirestore }) => {
    try {
      const firestore = getFirestore();

      // Get all firestore data nodes that will be used for updating after data change
      const userBudget = firestore
        .collection("users")
        .doc("asdfasdfas8128fsa")
        .collection("budget");
      const userDataRef = userBudget.doc("data");
      const userGeneralRef = userBudget.doc("general");

      // variables to be used in generating updated maps
      var grossIncome = 0;
      var netIncome = 0;
      var userDataMap = {};
      var userGeneralMap = {};

      // get grid data
      await userDataRef
        .get()
        .then(function(doc) {
          if (doc.exists) {
            userDataMap = doc.data();
          } else {
            console.log("No user data");
          }
        })
        .catch(function(error) {
          console.log("User Data Document Get Error: ", error);
        });
      // get header data
      await userGeneralRef
        .get()
        .then(function(doc) {
          if (doc.exists) {
            const data = doc.data();
            userGeneralMap = data;
            grossIncome = data.grossIncome;
            netIncome = data.netIncome;
          } else {
            console.log("No general data");
          }
        })
        .catch(function(error) {
          console.log("User General Document Get Error: ", error);
        });

      // generate new data and general document mappings
      const updatedMaps = generateUpdatedMaps(
        userDataMap,
        userGeneralMap,
        grossIncome,
        netIncome,
        inputData,
        fieldToUpdate
      );
      const newUserDataMap = updatedMaps.newDataMap;
      const newUserGeneralMap = updatedMaps.newGeneralMap;

      // update firestore data with new mappings
      userDataRef.set(newUserDataMap);
      userGeneralRef.set(newUserGeneralMap);

      toastr.success("Success!", "Budget data has been updated");
    } catch (error) {
      toastr.error("Oops", "Something went wrong");
    }
  };
};

我认为,通过将我的BudgetDashboard组件包装在firestoreConnect中,当发生更改但没有发生更改时,侦听器将自动更新。取而代之的是,只有在进行强制刷新时,我的LoadingComponent才会显示,新数据最终会反映在屏幕上。那么,如何进行任何更改以立即反映屏幕上的更改?

1 个答案:

答案 0 :(得分:0)

因此,假设您需要刷新的屏幕是“ screen1”。它会像这样:

import { NavigationActions, StackActions } from 'react-navigation';

default class Screen1 extends Component {
  constructor(props) {
    super(props);
  }

  <<stuff from your component>>   
}

const mapDispatchToProps = (dispatch, ownProps) => {
  goToHomeScreen: () => { 
    ownProps.navigation.dispatch(StackActions.reset({index: 0, key: null, actions: [NavigationActions.navigate({ routeName: '**<<ROUTE YOU WANT TO GO>>**'})]}))
  },
}

export default connect(mapDispatchToProps)(Screen1);

例如,从商店中获取数据后,需要刷新屏幕后,您将其命名为:

this.props.goToHomeScreen()

我希望这会有所帮助,不确定是否是您想要的东西,但这是我从商店获得新道具后发现刷新屏幕的一种方法。