在React Native中将对象的子属性映射到数组中

问题描述 投票:0回答:1

我尝试列出使用Google Places API加载的项目。我会毫不费力地收到标准值,并且可以在“文件夹”功能(例如item.name)中轻松阅读,但我也想使用照片。如果在我的“ componentWillMount” console.log中(this.state.drinks [0] .photos [0] .photo_reference); '输出我得到正确的值。但是,我无法在文件夹功能中执行此操作。那里我得到了错误:'TypeError:undefined不是对象(正在评估items.photos [0]')'

我的问题是,是否有人知道如何在map函数中管理对象的子对象?我必须在对象中将属性“照片”设置为“ photo_reference”。

我的代码:

 import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, Button, ScrollView, ImageBackground, Dimensions} from 'react-native';
import { Avatar, ListItem,Tile } from 'react-native-elements';
import firebase from 'react-native-firebase';
import Icon from 'react-native-vector-icons/FontAwesome';

import Slideshow from 'react-native-image-slider-show';




const initialLayout = { width: Dimensions.get('window').width };
class horecaScreen extends Component {

  constructor(props){
    super(props);
    this.state = {
      position: 1,
      interval: null,
      dataSource: [
        {
          title: 'Restaurant Rijk Van Margraten',
          caption: 'Bemelerweg 99, Cadier en Keer',
          url: 'https://firebasestorage.googleapis.com/v0/b/adventure-time-21e7c.appspot.com/o/dummy-eijsden.jpg?alt=media&token=87534c11-1280-4f54-a273-9f23225f9ab7',
        }, {
          title: 'Golfbaan het Rijk van Margraten',
          caption: 'Bemelerweg 99, Cadier en Keer',
          url: 'https://firebasestorage.googleapis.com/v0/b/adventure-time-21e7c.appspot.com/o/golfbaan-eijsden-margraten.jpg?alt=media&token=1cf1d9bf-5b63-4b51-8f68-1dd3df870af4',
        }, {
          title: 'Restaurant Rijk Van Margraten',
          caption: 'Bemelerweg 99, Cadier en Keer',
          url: 'https://firebasestorage.googleapis.com/v0/b/adventure-time-21e7c.appspot.com/o/dummy-eijsden.jpg?alt=media&token=87534c11-1280-4f54-a273-9f23225f9ab7',
        },
      ],
      drinks: [],
    }
  }


getUserData = (user) => {
  console.log(user);
  let ref = firebase.database().ref('Users/' + user);
  ref.on('value' , snapshot =>{
      var state = snapshot.val();
      this.setState({
        index: 0,
        routes:[
          {key: 'first', title: 'First'},
          {key: 'second', title: 'Second'}
        ]
      })
    })

}

photosPlaces = [];
drinksPlaces = [];

  componentWillMount(){
    let user = firebase.auth().currentUser;
    console.log(user);
    this.getUserData(user.uid); 
    let url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=50.97648620605469,5.780409336090088&radius=2000&type=bar&key=<API KEY>';
        fetch(url)
            .then((response) => response.json())
            .then((JsonResponse) => {
                // console.error(JsonResponse)
               console.log(JsonResponse.results)  

                this.setState({
                  drinks:  JsonResponse.results,
                })


                //console.log(this.state.drinks[0].photos[0].photo_reference);
            })
            .catch((error) => {
                alert('error')
            });


  }





  render() {


      return (


        <ScrollView style={styles.container}>
        <Slideshow 
        dataSource={this.state.dataSource}
        position={this.state.position}
        onPositionChanged={position => this.setState({ position })} 
        titleStyle={{color: 'white', fontWeight: 'bold'}}
        captionStyle={{color: 'white'}}
        arrowSize={0}
        onPress={({ index }) => this.props.navigation.navigate('HorecaDetail', {indexID: index})}
        />


        <View style={styles.Tiles}>
          <View style={styles.activity}> 
            <Text style={styles.activityText}>Iets drinken in de buurt?</Text>
            <ScrollView horizontal={true}>


                {
         this.state.drinks.length > 0 && this.state.drinks.map((item, i) =>(
            <View style={styles.listRow}>

              <ImageBackground source={{uri:'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + item.photos[0].photo_reference + '&key=<API KEY>'}} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10, borderRadius: 250 }}>
                <Text style={styles.insideText}>{item.name}</Text>
              </ImageBackground>
            </View>
          ))
        }


          </ScrollView>
          </View>
          </View>

          <View style={styles.Tiles}>
          <View style={styles.activity}> 
            <Text style={styles.activityText}>Iets eten in de buurt?</Text>
            <ScrollView horizontal={true}>
          <View style={styles.listRow}>
            <View style={styles.LeftColumn}>
            <ImageBackground source={require('../assets/images/all/dummy-location.png')} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10, borderRadius: 250 }}>
               <Text style={styles.insideText}>Bedrijf A</Text>
              </ImageBackground>
            </View>
            <View style={styles.RightColumn}>
            <ImageBackground source={require('../assets/images/all/dummy-location.png')} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10 , marginLeft: 5,}}>
               <Text style={styles.insideText}>Bedrijf B</Text>
              </ImageBackground>
              </View>
          </View>
          <View style={styles.listRow}>
            <View style={styles.LeftColumn}>
            <ImageBackground source={require('../assets/images/all/dummy-location.png')} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10, borderRadius: 250 }}>
               <Text style={styles.insideText}>Bedrijf A</Text>
              </ImageBackground>
            </View>
            <View style={styles.RightColumn}>
            <ImageBackground source={require('../assets/images/all/dummy-location.png')} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10 , marginLeft: 5,}}>
               <Text style={styles.insideText}>Bedrijf B</Text>
              </ImageBackground>
              </View>
          </View>
          </ScrollView>
          </View>
          </View>



          <View style={styles.bottomSpace}>

          </View>

        </ScrollView>

  );

}
  }

  const styles = StyleSheet.create({
    profileName:{
      fontWeight: 'bold',
      fontSize: 22,
      marginTop: 20,
    },
    list:{
      marginTop: 40,
      width: '100%'
    },
    scene: {
        flex: 1,
      },
    listRow:{
      flex: 1,
      flexDirection: 'row',
      flexWrap: 'wrap',
      alignItems: 'flex-start',
      paddingTop: 10,
      marginTop: -20,
      marginRight: 10
    },
    LeftColumn:{
      width: '50%',
      borderRadius: 250
    },
    RightColumn:{
      width: '50%',
    },
    Tiles:{
      padding: 10,

      marginTop: 20
    },
    insideText:{
      color: 'white',
      bottom: 0,
      alignContent: 'flex-end',
      fontWeight: 'bold'
    },
    bottomSpace:{
      padding: 10,
      marginTop: 30
    },
    Slideshow:{
      color: 'white'
    },
    activityText:{
      fontWeight: 'bold',
      fontSize: 18,
      marginBottom: 10,
    },
    iconOverview:{
      fontSize: 15,
      paddingRight: 120
    }
  })



  export default horecaScreen;

提取的输出:enter image description here

javascript react-native google-places-api
1个回答
0
投票

ComponentWillMount()生命周期方法已弃用,并且使用不安全。请改用ComponentDidMount()。

出现您的错误:'TypeError:未定义不是一个对象(正在评估'item.photos [0]')'

尝试做:

{
         this.state.drinks.length > 0 && this.state.drinks.map((item, i) =>(
            <View style={styles.listRow}>

              <ImageBackground source={{uri:'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + item.photos[0].photo_reference + '&key=AIzaSyCg9FZhTByAlhSrEMg1Bt4HtRuNWx4NcT8'}} style={{width: 140, height: 200, justifyContent: 'flex-end',paddingBottom: 10, paddingLeft: 10, borderRadius: 250 }}>
                <Text style={styles.insideText}>{item.name}</Text>
              </ImageBackground>
            </View>
          ))
        }
© www.soinside.com 2019 - 2024. All rights reserved.