Измените tabBarIcon при изменении состояния избыточности - PullRequest
0 голосов
/ 26 января 2020

Я определил navigationOptions в App.js для такого потока:

Приложение. js

const intimationsFlow = createStackNavigator({
  Feed: FeedContainer,
  Edit: EditContainer
});

intimationsFlow.navigationOptions = ({ navigation }) => {
  let tabBarVisible = true;
  if (navigation.state.index > 0)
    tabBarVisible = false;

  return {
    title: '',
    tabBarIcon: ({ focused }) => {
      const { pushNotificationSeen } = store.getState();
      console.log('pushNotificationSeen', pushNotificationSeen);

      let i;
      if(pushNotificationSeen) {
        if (focused) {
          i = <FontAwesomeIcon icon={'bell'} size={29} color={'#3780BE'} />
        } else {
          i = <FontAwesomeIcon icon={'bell'} size={29} color={'#393939'} />
        }
      } else {
        if (focused) {
          updatePushNotificationSeen(true);
          i = <FontAwesomeIcon icon={'bell'} size={29} color={'#3780BE'} />
        } else {
          i = <><FontAwesomeIcon icon={'bell'} size={29} color={'#393939'} /><Badge status="error" badgeStyle={{ position: 'absolute', top: -26, right: -13 }} /></>
        }
      }

      return i;
    },
    tabBarVisible
  };
};

const AppNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  mainFlow
});

const App = createAppContainer(AppNavigator);

export default () => {
  return <Provider store={store}>
    <SafeAreaProvider>
      <App ref={navigatorRef => { setTopLevelNavigator(navigatorRef) }} />
    </SafeAreaProvider>
  </Provider>
}; 

Я хочу обновить tabBarIcon в зависимости от того, было ли уведомление pu sh уже просмотрено или нет. Если уведомление pu sh еще не было просмотрено, вместо этого я показываю значок.

Проблема в том, что я могу получить состояние только при наличии активности на панели вкладок. Но я хочу, чтобы всякий раз, когда состояние pushNotificationSeen обновлялось, tarBarIcon должен был перерисовываться.

Пожалуйста, предложите, если это возможно иначе, как этого можно достичь. Спасибо.

Ответы [ 2 ]

0 голосов
/ 26 января 2020

Мне удалось найти достойное решение.

Что я действительно хотел, так это получить доступ к хранилищу резервов из компонента React Navigation . Реагирующие компоненты навигации, как и любые другие реактивные компоненты, могут быть подключены ed к хранилищу резервов. Однако в данном конкретном случае для подключения компонента реагирующей навигации я хотел создать настраиваемый расширенный навигатор в соответствии с этим предложением .

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Badge } from 'react-native-elements';
import { createStackNavigator } from 'react-navigation-stack';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { NavigationEvents } from 'react-navigation';

import FeedContainer from '../../screens/feed/FeedContainer';
import EditContainer from '../../screens/edit/EditContainer';
import { updatePushNotificationSeen } from '../../store/push-notification-seen/actions';

const IntimationsFlow = createStackNavigator({
    Feed: FeedContainer,
    Edit: EditContainer
});

class IntimationsFlowNavigator extends Component {

    static router = IntimationsFlow.router;

    static navigationOptions = ({ navigation }) => {
        let tabBarVisible = true;
        if (navigation.state.index > 0)
            tabBarVisible = false;

        return {
            title: '',
            tabBarIcon: ({ focused }) => {
                let i;
                if (!navigation.state.params || navigation.state.params.pushNotificationSeen) {
                    if (focused)
                        i = <FontAwesomeIcon icon={'bell'} size={29} color={'#3780BE'} />;
                    else
                        i = <FontAwesomeIcon icon={'bell'} size={29} color={'#393939'} />;
                } else {
                    if (focused)
                        i = <FontAwesomeIcon icon={'bell'} size={29} color={'#3780BE'} />;
                    else
                        i = <>
                            <FontAwesomeIcon icon={'bell'} size={29} color={'#393939'} />
                            <Badge status="error" badgeStyle={{ position: 'absolute', top: -26, right: -13 }} />
                        </>;
                }

                return i;
            },
            tabBarVisible
        };
    };

    componentDidUpdate(prevProps) {
        const { navigation, pushNotificationSeen } = this.props;
        if (pushNotificationSeen !== prevProps.pushNotificationSeen)
            navigation.setParams({ pushNotificationSeen });
    }

    render() {
        const { navigation } = this.props;
        return <>
            <NavigationEvents
                onDidFocus={() => { if (!this.props.pushNotificationSeen) updatePushNotificationSeen(true) }}
                onDidBlur={() => { if (!this.props.pushNotificationSeen) updatePushNotificationSeen(true) }}
            />
            <IntimationsFlow navigation={navigation} />
        </>;
    }
}

const mapStateToProps = ({ pushNotificationSeen }) => {
    return { pushNotificationSeen };
};

export default connect(mapStateToProps, null)(IntimationsFlowNavigator);

Каждый раз, когда в реквизите было обновление. Я устанавливал новое значение для navigation.state.params.pushNotificationSeen примерно так navigation.setParams({ pushNotificationSeen }); в методе жизненного цикла componentDidUpdate , чтобы использовать его в методе navigationOptions stati c. (Мы не можем напрямую получить доступ к компонентам в методе navigationOptions, так как он является членом c).

Любые побочные эффекты, которые необходимо выполнить для фокусировки / размытия вкладки, могут быть достигнуты с помощью NavigationEvents согласно этому предложению .

0 голосов
/ 26 января 2020

вы должны прослушать изменения pu sh в редукторе при componentWillReceiveProps

class YourComponent extends React.Component {
    {...}
    static navigationOptions = {
        title: ({ state }) => `there is ${state.params && state.params.pushNotificationSeen ? state.params.pushNotificationSeen : ''}`,
        {...}
    }
    {...}
    componentWillReceiveProps(nextProps) {
        if (nextProps.pushNotificationSeen) {
            this.props.navigation.setParams({ pushNotificationSeen });
        }
    }
}

const connectedSuperMan = connect(state => ({ pushNotificationSeen: state.ReducerYo.pushNotificationSeen }))(YourComponent);
...