【问题标题】:Access array of objects to display in React Native Text component访问要在 React Native Text 组件中显示的对象数组
【发布时间】:2016-08-22 09:52:34
【问题描述】:

我无法访问 JSON 数据中的对象数组以显示在 React Native Text 组件中。

JSON 数据

{
    "name": "Pizza Joint",
    "when": [{
        "day": ["Sat", "Sun"],
        "start_time": "11:00",
        "end_time": "23:00"
    }]
}

代码

<View style={styles.container}>
    <Text style={styles.name}>{venue.name}</Text>
    <Text style={styles.time}>{venue.when[0].start_time}</Text>
</View>

这会引发错误Undefined is not an object (evaluating 'venue.when'),我不明白,因为console.log(type of venue.when) 返回object

如何在此处访问when 对象属性?

补充说明

我从this tutorial复制了应用程序结构。

这里是VenueList.js

'use strict';

var React = require('react-native');
var VenueDetail = require('./VenueDetail');

var {
    Image,
    StyleSheet,
    Text,
    View,
    Component,
    ListView,
    TouchableHighlight,
    ActivityIndicatorIOS
   } = React;

var styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
        padding: 10
    },
    thumbnail: {
        width: 53,
        height: 81,
        marginRight: 10
    },
    rightContainer: {
        flex: 1,
    },
    title: {
        fontSize: 20,
        marginBottom: 8
    },
    author: {
        color: '#656565'
    },
    separator: {
        height: 1,
        backgroundColor: '#dddddd'
    },
    listView: {
           backgroundColor: '#F5FCFF'
       },
   loading: {
       flex: 1,
       alignItems: 'center',
       justifyContent: 'center'
   }
});

// var REQUEST_URL = 'https://www.googleapis.com/books/v1/volumes?q=subject:fiction';
var REQUEST_URL = 'http://apib.miniguide.es/wall/today';

class VenueList extends Component {

  render() {
    if (this.state.isLoading) {
      return this.renderLoadingView();
    }
    console.log(this.state.dataSource);

    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderVenue.bind(this)}
        style={styles.listView}
      />
    );
  }

  renderLoadingView() {
    return (
      <View style={styles.loading}>
        <ActivityIndicatorIOS
          size='large'/>
          <Text>
            Loading venues...
          </Text>
      </View>
    );
  }

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
      })
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(REQUEST_URL)
    .then((response) => response.json())
    .then((responseData) => {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(responseData),
        isLoading: false
      });
    })
    .done();
  }

  renderVenue(venue) {
    console.log(venue);
    return (
      <TouchableHighlight onPress={() => this.showVenueDetail(venue)} underlayColor='#dddddd'>
        <View>
          <View style={styles.container}>
            <Image
//              source={{uri: venue.images[0].url}}
              style={styles.thumbnail} />
            <View style={styles.rightContainer}>
              <Text style={styles.title}>{venue.name}</Text>
              <Text style={styles.author}>{venue.subtitle}</Text>
            </View>
          </View>
          <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    );
  }
}

module.exports = VenueList;

console.log(venue) 产生以下格式的数据(出于示例的目的,我在这里简化了输出):

{
    name: 'Pizza Joint',
        when: [{
            day: ['Sat', 'Sun'],
            start_time: '11:00',
            end_time: '23:00'
        }]
}

我注意到上面不是 JSON,因为键上的引号已被删除。

【问题讨论】:

  • {venue.when[0].start_time]} 一个错字,你写的是{venue.when[0].start_time} 吗?
  • 是的,打错了,抱歉
  • 渲染代码中的路径访问似乎是正确的,您在渲染函数中传递venue的方式一定有问题。在渲染之前尝试控制台记录场地对象。
  • venue 如何暴露给您的组件?您是否正在遍历场地列表?你能在渲染视图之前显示console.log(venue) 的输出吗?
  • 你是否也设置了场地的初始状态,因为如果没有,它会在你发出获取请求之前开始为空。

标签: javascript json reactjs react-native


【解决方案1】:

好的,我想通了。问题是我们的 API 生成的 JSON 数据集包含一些文档,这些文档具有另一个定义来分隔数据(例如,第一个是指示 featured 的文档)。所以 React 在第一个文档上抛出了一个错误,它缺少我试图访问的属性。

为了解决这个问题,我在 React 组件中添加了三元表达式来检查属性是否存在:

  renderVenue(venue) {
    console.log(venue);
    return (
      <TouchableHighlight onPress={() => this.showVenueDetail(venue)} underlayColor='#dddddd'>
        <View>
          <View style={styles.container}>
            <Image source={ 'images' in venue ? { uri: 'http://' + venue.images[0].url } : null}       
              style={styles.thumbnail} />
            <View style={styles.rightContainer}>
              <Text style={styles.title}>{venue.name}</Text>
              <Text style={styles.author}>{venue.subtitle}</Text>
              <Text style={styles.author}>{ 'when' in venue ? venue.when[0].start_date : null}</Text>
            </View>
          </View>
          <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    );
  }
}

也许我们应该修改我们的 API 输出。

无论如何感谢 cmets,他们很有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多