好的,所以我不确定这是否是处理此问题的最佳方法,但我找到了一种让我的通知正常工作的方法。
(1) 我创建了一个名为 registerAppLoaded 的操作和一个状态变量 appLoaded,一旦我的 AppLoading 组件完成其 startAsync 函数,我就会调度它们。
(2) 收到通知时,我首先检查appLoaded 是否为真。如果是这样,我会导航到与通知一起发送的目的地。如果没有,我将通知放在商店中并继续启动应用程序。
(3)在AppLoadingonFinish函数中,我查看是否有通知。如果是这样,并且它被标记为new,我抓住它并使用参数进行导航。然后我发送一个设置navigation.new = false的动作
似乎完全按照我需要的方式工作!
如果其他人正在处理这个问题,这是我的代码:
App.tsx:
export default class App extends React.Component {
componentDidMount() {
Notifications.addListener((notification) => {
if (notification.origin === "received") {
return;
} else {
const appLoaded = store.getState().general.appLoaded
if (appLoaded) {
NavigationService.navigate(notification.data.navigate, {id:notification.data.id , shouldRefresh: true})
} else {
// save notification as new
store.dispatch(addNotification(notification, true));
}
};
})
}
render() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<View style={styles.container}>
{Platform.OS === "ios" && <StatusBar barStyle="default" />}
<ErrorBoundary backup={<AppError />}>
<AppNavigator />
</ErrorBoundary>
</View>
</PersistGate>
</Provider>
);
}
}
AppLoading.tsx:
class AppLoadingScreen extends React.Component {
_loadResourcesAsync = async() => {
await this.props.fetchUserOnboarding(this.props.userId);
if (this.props.userDevice && this.props.userDevice.id) {
this.props.registerUserDevice(this.props.userId, this.props.userDevice.id)
}
// register that the app has finished loading in the store; this will be used to determine if a notification's deep
// link should be immediatedly navigated to or if the navigation even shuold be deferred until after the app
// finishes loading
await this.props.registerAppLoaded()
};
_handleFinishLoading = async () => {
// if a notification triggers the event listener but the app is not yet fully loaded, the deep link will be
// navigated to here instead of directly from the listener
const notification = this.props.userNotifications && this.props.userNotifications[0]
if (notification && notification.new && notification.origin != 'recieved') {
this.props.addNotification(notification, false) // set notification.new = false
this.props.navigation.navigate(notification.data.navigate, {id: notification.data.id, shouldRefresh: true})
} else if (this.props.showGoalsPrompt) {
this.props.navigation.navigate("Goal");
} else {
this.props.navigation.navigate("HomeFeed");
}
};
render() {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onFinish={this._handleFinishLoading}
/>
);
}
}
actions.tsx:
export const registerAppLoaded = () => {
return dispatch => {
dispatch({
type: types.REGISTER_APP_LOADED,
payload: true
});
};
}
export const addNotification = (notification, isNew=false) => {
return dispatch => {
notification.new = isNew // indicate whether this is a new notification or if it has been seen
dispatch({
type:types.ADD_USER_NOTIFICATION,
payload: notification,
})
};
}