react-native - 使用博览会通知处理传入通知

标签 react-native redux react-redux expo expo-notifications

我对以下代码示例有疑问:

Notifications.setNotificationHandler({//makes sure notification is displayed even when app is open, nothing else
    handleNotification: async (notification) => {
        //const value = await AsyncStorage.getItem('presetlanguage');
        //console.log("ASYNC STORAGE LANGUAGE FROM OUTSIDEEEE: ", value)
        //if(notification.request.content.body == "You received a new letter from a PigeonBuddy!"){
        //    console.log("hat geklappt")
        //}
        return{
            shouldShowAlert: true
        };
    }
});

const MainScreen = props => {
    const dispatch = useDispatch();
    var chosenLanguage = useSelector(state => state.myLanguage.myLanguage); ...........
setNotificationHandler负责处理传入的通知,因此我想过滤传入的通知。例如,根据我在哪个屏幕上,我想显示或不显示通知。 然而,问题是,我既无法访问导航状态,也无法访问 redux 状态 因为这种通知的处理发生在默认屏幕主函数之外,该函数涵盖了所有变量并且还通过导航使用 Prop 。禁止在那里调用 redux 钩子(Hook),而且我也无法访问我的导航状态,因为我无法访问我通过导航获得的 props 变量。
如何根据我所在的屏幕显示我的通知?像 Facebook 这样的公司是如何做到的?如果您在聊天屏幕上,您不会收到通知,但如果您在外面,则会显示“收到来自...的新消息”的通知。

最佳答案

您可以导出导航引用

export const navRef = React.createRef();

const App = () => {
  return (
    <NavigationContainer ref={navRef}>
      ...
    </NavigationContainer>
  );
};
并使用它来获取您所在的屏幕,在 setNotificationHandler 中
const currentRouteName = navRef.current.getCurrentRoute().name;
可以使用类似的代码。此代码适用于 react 导航 v6
已编辑
react 导航 v4
创建一个 reactRef 使用 onNavigationStateChange 跟踪当前屏幕。
export const currentScreenRef = React.createRef('Splash');

function getActiveRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  if (route.routes) {
    return getActiveRouteName(route);
  }
  return route.routeName;
}

const App = () => {
  return (
    <NavigationContainer 
      onNavigationStateChange={(prevState, currentState) => {
        const currentRouteName = getActiveRouteName(currentState);
        currentScreenRef.current = currentRouteName;
      }}
    >
      ...
    </NavigationContainer>
  );
};
所以可以称之为
const currentRouteName = currentScreenRef.current;
注意:未测试,因为没有任何运行 V4 的项目。如果不起作用或需要编辑,请添加评论

关于react-native - 使用博览会通知处理传入通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68950451/

相关文章:

reactjs - 使用 redux saga 时等待 redux action 完成调度

javascript - Redux:调用 action-creator 返回 'Cannot read property ' props' of undefined'

redux - Redux createSelector() 跨多个组件的记忆化如何中断?

react-native - 无法加载脚本。确保您正在运行 Metro 服务器(运行 'react-native start' )或您的包 'index.android.bundle'

javascript - 进行 ajax 调用后如何呈现结果?

react-native - Victory Native 饼图动画

android - React Native DrawerLayoutAndroid 引用不起作用

javascript - 改变状态的函数的 Redux 词

javascript - Redux - 正确调度操作

javascript - React 组件不会在 window.location 更改时重新渲染