我有一个从Firebase实时数据库加载用户数据的功能。该函数调用在主加载屏幕(在componentDidMount
中)加载数据的操作。问题在于,加载页面在完成加载之前会导航到主屏幕(从Firebase提取数据并调度)。
在应用程序开始时被调用的功能运行:
async componentDidMount(){
....
if (facebookToken !== null){
await this.props.loadData();
this.props.navigation.navigate("MainScreen");
....
}
和被调用的动作:
export const loadData = () => async dispatch => {
firebase.auth().onAuthStateChanged((user) => {
dispatch({ type: SAVE_USER, payload: {prop: "uid", value: user.uid}});
firebase.database().ref(`/users/${user.uid}`)
.once('value', snapshot => {
dispatch({type: UPDATE_CREDENTIALS, payload: { prop: "phone", value: snapshot.val().phone}});
dispatch({type: UPDATE_CREDENTIALS, payload: { prop: "country", value: snapshot.val().country}});
dispatch({ type: SAVE_USER, payload: {prop: "name", value: snapshot.val().name}});
dispatch({ type: SAVE_USER, payload: {prop: "fbPicture", value: snapshot.val().photo}});
})
}
});
...
}
我似乎找不到有效的解决方案,以便在数据调用继续导航到MainScreen
答案 0 :(得分:1)
答案 1 :(得分:0)
好,我找到了解决方案:)
我在操作调用中添加了.then
语句,这样:
async componentDidMount(){
....
if (facebookToken !== null){
await this.props.loadData().then(() => {
this.props.navigation.navigate("MainScreen"); })
....
}
,在该操作中,我用return new Promise()
包装了函数调用,并在完成所有调度调用后使用了resolve()
:
return new Promise( (resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
dispatch({ type: SAVE_USER, payload: {prop: "uid", value: user.uid}});
firebase.database().ref(`/users/${user.uid}`)
.once('value', snapshot => {
if (snapshot.val() !== null){
dispatch({type: UPDATE_CREDENTIALS, payload: { prop: "phone", value: snapshot.val().phone}});
dispatch({type: UPDATE_CREDENTIALS, payload: { prop: "country", value: snapshot.val().country}});
dispatch({ type: SAVE_USER, payload: {prop: "name", value: snapshot.val().name}});
dispatch({ type: SAVE_USER, payload: {prop: "fbPicture", value: snapshot.val().photo}});
}
resolve();
});
});
})