Невозможно прочитать свойство 0 неопределенного - PullRequest
0 голосов
/ 21 сентября 2018

Я отчаянно пытался решить эту проблему, но все еще растерялся.Ошибка «Не удается прочитать свойство 0 неопределенного» при попытке передать массив gallery [], в котором фотографии имеют первый (0) индекс.

Я убедился, что галерея массивов существует и в правильном формате, когда я его утешаю.Однако я не уверен, почему возвращаются 2 оператора консоли, причем первое не определено, а второе - правильно.

Подробнее см. Ниже фрагменты кода и снимок экрана.Я буду признателен за вашу помощь, поскольку я полностью потерян.Это единственный аспект, откладывающий завершение разработки моего приложения.Спасибо

 <Text style={styles.sectionHeader}> Photo Galery</Text>
          <View >
            {console.log(gallery)}
         {  

                <TouchableOpacity  >
                    <Image 
                        source={gallery[0].photos}
                        style={styles.navImageStyle}
                    />
                </TouchableOpacity>

        }

Вот скриншот с правильным определением объекта галереи.Я испробовал все виды ссылок на него в своем теге изображения (даже используя source = {{uri: gallery [0] .photos}}, но не повезло.

gallery object logged to the console

Когда я изменяю тег изображения с source = {gallery}, изображения вообще не отображаются, хотя я знаю, что синтаксис неполон. См. Изображение ниже.

screen missing images under Photo Gallery Heading

--- Более подробная информация приведена ниже для каждого запроса ----- Массив галереи взят из локального массива данных (placeData), который импортируется с помощью приведенного ниже кода. Затем код импортирует галерею как объект вмодальное окно (SiteDetails) при нажатии кнопки

import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import { ListItem, } from 'native-base';

import { placesData } from '../../data/placesData';
import Places from '../../data/Places';
import SiteDetails from '../SiteDetails';

export default class NavPlaces extends Component {
  constructor(props) {
    super(props);
    this.state = {
        setModalVisible: false,
        modalArticleData: {},
        error: null
    };
  }


_handleItemDataOnPress = articleData => {
  this.setState({
    setModalVisible: true,
    modalArticleData: articleData
  });
};

_handleModalClose = () => {
  this.setState({
    setModalVisible: false,
    modalArticleData: {}
  });
};

  render() {
    return (
        <View>
          <FlatList
              data={placesData}
              renderItem={({ item }) => (
                  <ListItem style={{ marginLeft: 5,}}>
                      <Places  onPress={this._handleItemDataOnPress} data={item} />               
                  </ListItem>
              )}
              horizontal={true}
              keyExtractor={item => item.id}
          />
          <SiteDetails
            showModal={this.state.setModalVisible}
            articleData={this.state.modalArticleData}
            onClose={this._handleModalClose}
          />
        </View>
    );
  }
}

SiteDetails

import React, { Component } from "react";
import Icon from "react-native-vector-icons/FontAwesome";

import {
  FlatList,
  Dimensions,
  Modal,
  ScrollView,
  Share,
  TouchableOpacity, Image, Text, View,
} from "react-native";

import {
  Grid, Row, Col,
  Header,
  ListItem,
  Content,
  Container,
  Body,
  Left,
  Right,
  Title,
} from "native-base";
// import PlacePhoto from '../data/PlacePhoto';
// import NavGallery from "./Tabs/NavGallery";
// import {placesData} from '../data/placesData'

const webViewHeight = Dimensions.get("window").height - 56;
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;

export default class SiteDetails extends Component {
  constructor(props) {
    super(props);
    this.data = props.data;
}

  _handleClose = () => {
    return this.props.onClose();
  };

  _handleShare = (clickedLink, clickedTitle) => {
    // const { link,title } = this.props.data;
    message = `${clickedTitle}\n\nRead more @\n${clickedLink.toString()}\n\nshared via MSU mobile`;
    return Share.share(
      { clickedTitle, message, url: message },
      { dialogTitle: `Share ${clickedTitle}` }
    );
  };

  render() {
    const { showModal, articleData } = this.props;
    const { image, title, subTitle, description,location, phone, credit, gallery } = articleData;

    // if (image !== undefined) {
      return (
        <Modal
          onRequestClose={this._handleClose}
          visible={showModal}
          transparent
          animationType="slide"
        >
          <Container
            style={{ margin: 0, marginBottom: 0, backgroundColor: "#ffffff" }}
          >
            <Content contentContainerStyle={{ height: webViewHeight }}>
              <Header
                style={{ backgroundColor: "#1b4383" }}
                iosBarStyle="light-content"
              >
                <Left>
                  <TouchableOpacity onPress={() => this._handleClose()}>
                    <Icon
                      name="close"
                      style={{ fontSize: 25, color: "#f47937", paddingHorizontal: 10, }}
                    />
                  </TouchableOpacity>
                </Left>
                <Body>
                  <Title
                    children={title}
                    style={{ color: "#ffffff" }}
                  />
                </Body>
                <Right>
                  <TouchableOpacity
                    // onPress={() =>
                    //   this._handleShare(articleData.link, articleData.title)
                    // }
                  >
                    <Icon
                      name="share-alt"
                      style={{ fontSize: 30, color: "#f47937", paddingHorizontal: 10, }}
                    />
                  </TouchableOpacity>
                </Right>
              </Header>

              <ScrollView>
                  <Image 
                    source={image}
                    style={styles.drawerCover}
                  />

              <View style={{backgroundColor: 'black',  }}>
                  <Text style={styles.titleText}>{title}</Text>
                  <View style={{ height: 16 }}/>
                  <Text style={styles.subTitleText}>{subTitle}</Text>
                  <View style={{ height: 16 }}/>

                  <Grid>
                  <Row>
                      <Col style={{ flexDirection: 'row'}}>
                        <Icon 
                          name='map-o'
                          style={styles.iconStyle}
                        />
                        <Text style={styles.subText}>location:</Text>
                      </Col>
                      <Col>
                        <Text style={styles.subText}>{location}</Text>
                      </Col>
                    </Row>
                    <View style={{ height: 16 }}/>
                    <Row>
                      <Col style={{ flexDirection: 'row'}}>
                        <Icon 
                          name='phone'
                          style={styles.iconStyle}
                        />
                        <Text style={styles.subText}>tel:</Text>
                      </Col>
                      <Col>
                        <Text style={styles.subText}>{phone}</Text>
                      </Col>
                    </Row>
                    <View style={{ height: 16 }}/>
                    <Row>
                      <Col style={{ flexDirection: 'row'}}>
                        <Icon 
                          name='globe'
                          style={styles.iconStyle}
                        />
                        <Text style={styles.subText}>Website:</Text>
                      </Col>
                      <Col>
                        <Text style={styles.subText}></Text>
                      </Col>
                      </Row>
                      <View style={{ height: 16 }}/>
                    <Row>
                      <Col style={{ flexDirection: 'row'}}>
                        <Icon 
                          name='pencil'
                          // name='creative-commons'
                          style={styles.iconStyle}
                        />
                        <Text style={styles.subText}>Credit:</Text>
                      </Col>
                      <View style={{ height: 16 }}/>
                      <Col>
                        <Text style={styles.subText}>{credit}</Text>
                      </Col>
                      </Row>

                  </Grid>
              </View>
              <Text style={styles.sectionHeader}> Photo Galery</Text>
              <View >
                {console.log(gallery)}
             {  

                    <TouchableOpacity  >
                        <Image 
                            source={gallery}
                            style={styles.navImageStyle}
                        />
                    </TouchableOpacity>

            }


              <Text style={styles.sectionHeader}> Description </Text>
              <Text style={styles.bodyText}> {description} </Text>
              </View>

              </ScrollView>
            </Content>
          </Container>
        </Modal>
      );
    // } else {
    //   return null;
    // }
  }
}

массив placeData:

export const placesData = 

[{id: 'a', изображение: требуется('../../assets/img/places/museum/slave/slavePic.jpg'), название: «Музей работорговли», подзаголовок: «Одна из многих редких жемчужин истории и образования», место нахождения: «Бадагри, Лагос ', телефон:' ', кредит:' Институт Фримена ', галерея: [{key:' v1 ', фотографии: [require (' ../../ assets / img / place / museum / slave / abolitionCannon).jpg '),требовать ('../../ assets / img / графы / места / музей / раб / holdingCell.jpg'), требовать ('../../ assets / img / графы / музей / раб / slaveMarket.jpg'),требовать ('../../ assets / img / графы / места / музей / раб / slaveNoReturn.jpg'), требовать ('../../ assets / img / места / музей / раб / bibleAtBadagry.jpg'),require ('../../ assets / img / place / museum / slave / bridge.jpg'),]
}], описание: 'Выдержки из Института Фримена',

},
{
    id: 'b',
    image: require('../../assets/img/places/parks/yankari.png'),
    title: 'Parks and WildLife',
    subTitle: 'Visit to this wildlife park will rejuvenate your mind and spirit',
    location: 'Jos, Lagos, Calabar, Abuja, etc',
    phone: '',
    credit: 'The Freeman Institute',
    gallery:[
        {
            id: 'v2',
            photos: [

                  require('../../assets/img/places/parks/ikogosi.png'),
                  require('../../assets/img/places/parks/abujaPark.png'),
                  require('../../assets/img/places/parks/raindeer.png'),
                  require('../../assets/img/places/parks/kainji.png'),
                  require('../../assets/img/places/parks/elephant.png'),
                  require('../../assets/img/places/parks/owuH2OFalls.png'),
            ]
        }
    ],
    description: 'Excerpts from online wiki',

},
{
    id: 'c',
    image: require('../../assets/img/places/resorts/badagry.png'),
    title: 'Resorts and Beaches',
    subTitle: 'Simply exquisite vacation sites, peaceful and beautiful beaches. Go on horseback riding or whatever suits you.',
    location: 'Lagos, Calabar, Abuja, etc',
    phone: '',
    credit: 'Online wiki',
    gallery:[
        {
            id: 'v3',
            photos: [
                  require('../../assets/img/places/resorts/funtopiaPark.png'),
                  require('../../assets/img/places/resorts/barBeach.png'),
                  require('../../assets/img/places/resorts/obudu.png'),
                  require('../../assets/img/places/resorts/funtopiaPark.png'),
                  require('../../assets/img/places/resorts/whisperingPalms.png'),
                  require('../../assets/img/places/resorts/tinapa.png'),
            ]
        }
    ],
    description: 'Excerpts from online wiki',

},
{
    id: 'd',
    image: require('../../assets/img/places/museum/museumBeni.png'),
    title: 'National Musuems',
    subTitle: 'Incredible museums of history and education with variety to enrich the minds.',
    location: 'Lagos, Jos, Kaduna, Enugu, Benin, etc',
    phone: '',
    credit: 'Ministry of Tourism',
    gallery:[
        {
            id: 'v4',
            photos: [
                  require('../../assets/img/places/museum/museumLagos.jpg'),
                  require('../../assets/img/places/museum/museumWar.jpg'),
                  require('../../assets/img/places/museum/museumKaduna.jpg'),
                  require('../../assets/img/places/museum/museumOwo.jpg'),
                  require('../../assets/img/places/museum/museumColonia.jpg'),
                  require('../../assets/img/places/museum/museumOwo.jpg'),
            ]
        }
    ],
    description: 'Excerpts from online wiki',

},

]

// export const placesData = 
// [
//     {
//         id: 'a',
//         image: require('../../assets/img/places/museum/slave/slavePic.jpg'),
//         title: 'Slave Trade Museum',
//         subTitle: 'One of many rare gems of history and education',
//         location: 'Badagry, Lagos',
//         phone: '',
//         credit: 'The Freeman Institute',
//         photos:{
//             key: 'a1',
//             pic1: require('../../assets/img/places/museum/slave/abolitionCannon.jpg'),
//             pic2: require('../../assets/img/places/museum/slave/holdingCell.jpg'),
//             pic3: require('../../assets/img/places/museum/slave/slaveMarket.jpg'),
//             pic4: require('../../assets/img/places/museum/slave/slaveNoReturn.jpg'),
//             pic5: require('../../assets/img/places/museum/slave/bibleAtBadagry.jpg'),
//             pic6: require('../../assets/img/places/museum/slave/bridge.jpg'),
//         },
//         description: 'Excerpts from Freeman Institute',

//     },
//     {
//         id: 'b',
//         image: require('../../assets/img/places/parks/yankari.png'),
//         title: 'Parks and WildLife',
//         subTitle: 'Visit to this wildlife park will rejuvenate your mind and spirit',
//         location: 'Jos, Lagos, Calabar, Abuja, etc',
//         phone: '',
//         credit: 'The Freeman Institute',
//         photos:{
//             key: 'b1',
//             pic1: require('../../assets/img/places/parks/ikogosi.png'),
//             pic2: require('../../assets/img/places/parks/abujaPark.png'),
//             pic3: require('../../assets/img/places/parks/raindeer.png'),
//             pic4: require('../../assets/img/places/parks/kainji.png'),
//             pic5: require('../../assets/img/places/parks/elephant.png'),
//             pic6: require('../../assets/img/places/parks/owuH2OFalls.png'),
//         },
//         description: 'Excerpts from online wiki',

//     },
//     {
//         id: 'c',
//         image: require('../../assets/img/places/resorts/badagry.png'),
//         title: 'Resorts and Beaches',
//         subTitle: 'Simply exquisite vacation sites, peaceful and beautiful beaches. Go on horseback riding or whatever suits you.',
//         location: 'Lagos, Calabar, Abuja, etc',
//         phone: '',
//         credit: 'Online wiki',
//         photos:{
//             key: 'c1',
//             pic1: require('../../assets/img/places/resorts/funtopiaPark.png'),
//             pic2: require('../../assets/img/places/resorts/barBeach.png'),
//             pic3: require('../../assets/img/places/resorts/obudu.png'),
//             pic4: require('../../assets/img/places/resorts/funtopiaPark.png'),
//             pic5: require('../../assets/img/places/resorts/whisperingPalms.png'),
//             pic6: require('../../assets/img/places/resorts/tinapa.png'),
//         },
//         description: 'Excerpts from online wiki',

//     },
//     {
//         id: 'd',
//         image: require('../../assets/img/places/museum/museumBeni.png'),
//         title: 'National Musuems',
//         subTitle: 'Incredible museums of history and education with variety to enrich the minds.',
//         location: 'Lagos, Jos, Kaduna, Enugu, Benin, etc',
//         phone: '',
//         credit: 'Ministry of ?',
//         photos:{
//             key: 'd1',
//             pic1: require('../../assets/img/places/museum/museumLagos.jpg'),
//             pic2: require('../../assets/img/places/museum/museumWar.jpg'),
//             pic3: require('../../assets/img/places/museum/museumKaduna.jpg'),
//             pic4: require('../../assets/img/places/museum/museumOwo.jpg'),
//             pic5: require('../../assets/img/places/museum/museumColonia.jpg'),
//             pic6: require('../../assets/img/places/museum/museumOwo.jpg'),
//         },
//         description: 'Excerpts from online wiki',

//     },
// ]
...