我正在实现一个功能,该功能可以从Firebase数据库检索一些信息,然后将其显示在屏幕上。这是我在Redux操作文件上拥有的功能
export function getUserEventPreferences() {
return async dispatch => {
try {
const userId = auth().currentUser.uid;
const snapshot = await database().ref(`/users/${userId}`).once('value');
const isAir = (snapshot.val() && snapshot.val().isAir);
const isAnimals = (snapshot.val() && snapshot.val().isAnimals);
const isArtAndCulture = (snapshot.val() && snapshot.val().isArtAndCulture);
const isConcerts = (snapshot.val() && snapshot.val().isConcerts);
const isEducation = (snapshot.val() && snapshot.val().isEducation);
const isFood = (snapshot.val() && snapshot.val().isFood);
const isParty = (snapshot.val() && snapshot.val().isParty);
const isShopping = (snapshot.val() && snapshot.val().isShopping);
const isSports = (snapshot.val() && snapshot.val().isSports);
const data = {
isAir,
isAnimals,
isArtAndCulture,
isConcerts,
isEducation,
isFood,
isParty,
isShopping,
isSports
};
dispatch(showPrefereces(data));
} catch (e) {
console.log(e);
}
};
}
然后,在另一个名为UserProfilePreferencesController.js
的文件中,我在componentDidMounth
函数中调用此redux函数以检索信息
async componentDidMount() {
const { dispatchGetMyEventPreferences } = this.props;
// This is where I call the redux function
dispatchGetMyEventPreferences();
this.loadPreferences();
}
我的问题是,即使检索信息后,除非刷新应用程序,信息也不会显示在屏幕上。我该如何解决这个问题?
我尝试通过(通过this.loadPreferences()
函数)加载有关控制器状态的信息,但这似乎没有任何影响。
loadPreferences = () => {
const { login } = this.props;
this.setState({
isArtAndCulture: login.userEventCategoriesPreferences.isArtAndCulture,
isConcerts: login.userEventCategoriesPreferences.isConcerts,
isSports: login.userEventCategoriesPreferences.isSports,
isFood: login.userEventCategoriesPreferences.isFood,
isEducation: login.userEventCategoriesPreferences.isEducation,
isAnimals: login.userEventCategoriesPreferences.isAnimals,
isParty: login.userEventCategoriesPreferences.isParty,
isAir: login.userEventCategoriesPreferences.isAir,
isShopping: login.userEventCategoriesPreferences.isShopping
});
}
答案 0 :(得分:1)
“ componentDidMounth”在任何组件的生命周期方法中仅调用一次。
现在为什么不加载数据,因为您正在以异步方法获取数据。 函数“ this.loadPreferences();”在dispatchGetMyEventPreferences之后调用,但它在数据来自Firebase之前执行。
当数据来自Firebase时,尝试从dispatchGetMyEventPreferences返回一个Promise,然后调用this.loadPreferences();