Реагировать на нативную навигацию с редуксом

У меня есть компонент почтового ящика, который получает все уведомления с сервера и перечисляет их в представлении. Код для которого выглядит так,

import React, { Component } from 'react'
import {
  View,
  FlatList,
  ActivityIndicator,
  TouchableOpacity
} from 'react-native'

import {List, ListItem, SearchBar} from 'react-native-elements'
import Header from '../common/Header'
import { Container } from 'native-base'
import PushNotifications from '../../fcm/notifications/PushNotifications'
import NotificationDetails from './NotificationDetails';

export const Navigator = new StackNavigator({
  NotificationList: { screen: NotificationList },
  NotificationDetail: { screen: NotificationDetail },
},{
  initialRouteName: 'NotificationList',
})

class NotificationList extends Component {
  constructor(props) {
    super(props)

    this.state = {
      loading: false,
      data: [],
      page: 1,
      seed: 1,
      error: null,
      refreshing: false
    }
    this.loadNotificationDetails = this.loadNotificationDetails.bind(this)
  }

  componentDidMount() {
    const{dispatch,actions} = this.props
    dispatch(actions.getNotification())
  }

  handleRefresh = () => {
    this.setState(
      {
        page: 1,
        seed: this.state.seed + 1,
        refreshing: true
      },
      () => {
        const{dispatch,actions} = this.props
        dispatch(actions.getNotification())
      }
    )
  }

  handleLoadMore = () => {
    this.setState(
      {
        page: this.state.page + 1
      },
      () => {
        const{dispatch,actions} = this.props
        dispatch(actions.getNotification())
      }
    );
  }
  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />
  }

  renderFooter = () => {
    if (!this.state.loading) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#CED0CE"
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    )
  }

  loadNotificationDetails = () => {
    this.props.navigation.navigate('NotificationDetails')
  }

  render() {
    return (
      <Container >
        <Header />
        <List containerStyle={{ marginTop: 0, borderTopWidth: 0, borderBottomWidth: 0 }}>
          <FlatList
            data={this.props.listNotification}

            renderItem={({ item }) => (
              <TouchableOpacity
                onPress={() => this.loadNotificationDetails()}>
                <ListItem
                  roundAvatar
                  title={`${item.text}`}
                  subtitle={item.dateTime}
                  // avatar={{ uri: item.picture.thumbnail }}
                  containerStyle={{ borderBottomWidth: 0 }}
                />
              </TouchableOpacity>
            )}
            ItemSeparatorComponent={this.renderSeparator}
            ListHeaderComponent={this.renderHeader}
            ListFooterComponent={this.renderFooter}
            onRefresh={this.handleRefresh}
            refreshing={this.state.refreshing}
            onEndReached={this.handleLoadMore}
            onEndReachedThreshold={50}
          />
        </List>
        <PushNotifications />
      </Container>
    )
  }
}

export default NotificationList;

Теперь то, чего я хочу добиться, - это щелкнуть любой элемент списка, я хочу загрузить полное подробное уведомление. Что происходит, когда я нажимаю, кажется, что отсутствует объект навигации. Следовательно, его жалоба не может найти свойство навигации. У реквизита есть только элементы из хранилища избыточности, я не могу понять, как мне получить навигационные реквизиты в этот компонент, который уже имеет реквизит из хранилища избыточности? Как мне этого добиться? Буду признателен за любую оказанную помощь.

Спасибо, Викрам


person Vikram Mahishi    schedule 09.06.2018    source источник


Ответы (1)


StackNavigator — это фабричная функция, а не конструктор. Вы пробовали

const Navigator = StackNavigator({
  NotificationList: { screen: NotificationList },
  NotificationDetail: { screen: NotificationDetail },
},{
  initialRouteName: 'NotificationList',
})

Это немного сбивает с толку, однако в v2 команда изменила API на createStackNavigator.

person maxhungry    schedule 10.06.2018
comment
Я не понимаю вашего ответа, разве я уже не сделал это? Я хочу знать, как навигация получает правильные реквизиты? - person Vikram Mahishi; 10.06.2018
comment
Обратите внимание на new StackNavigator() против StackNavigator() - person maxhungry; 10.06.2018