在ListView,React-Native中迭代renderRow中的对象数组

时间:2017-04-19 10:30:15

标签: listview reactjs react-native axios react-native-listview

有下面的代码, 如何在移动设备屏幕上显示各种属性? 我能够看到控制台上打印出的对象数组,但是我无法使用每个对象中包含的属性来显示移动屏幕上的信息。

import React, { Component } from 'react';
import { AppRegistry, ListView, View, Text } from 'react-native';
import axios from 'axios';

export default class Component5 extends Component {
  constructor() {
    super();
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    this.state = {
      userDataSource: ds,
    };
  }
  componentDidMount() {
    this.fetchUsers();
  }
  fetchUsers() {
    axios.get('https://stageapi6.devmn.net/api/v1/forums/threads?topic_id=2418', {
      headers: {
        'client-id': '********'
      }
    })
    .then(response => this.setState({ userDataSource: this.state.userDataSource.cloneWithRows(response) }));
  }

  renderRow = (user) => {
    console.log(user); // => [Object, Object, Object, Object .........]

    return (
      <View>
        {/* I need a way to iterate the bojects and display the properties inside teh Text tags, the code below doesn't work */}
        <Text>{user.thread.num_posts}</Text> 
        <Text>{user.thread.topic_name}</Text>
        <Text>{user.thread.name}</Text>
      </View>
    );
  }
    render() {
      return (
        <ListView
          dataSource={this.state.userDataSource}
          renderRow={(user) => this.renderRow(user.threads)}
        />
      );
    }
}

AppRegistry.registerComponent('Component5', () => Component5);

SCREENSHOT OF THE RETURNED ARRAY OF OBJECTS AND ITS PROPERTIES

2 个答案:

答案 0 :(得分:2)

您需要迭代user数组并动态构建jsx。使用类似下面的内容

renderRow = (user) => {
 return (
  <View>
    { user.map(u =>
             (<View key={u.thread.id}>
              <Text>{u.thread.num_posts}</Text> 
              <Text>{u.thread.topic_name}</Text>
              <Text>{u.thread.name}</Text>
              <View>));
    }
  </View>
 );
}

答案 1 :(得分:0)

我无法对之前的答案发表评论,但它应该有效。如果它为您提供了您在上面发布的错误Cannot read property 'map' of undefined,该错误表明您传入user的{​​{1}}参数不是数组,或者它是空的,或者它有一个问题。专注于解决这一部分。

我将renderRow函数的代码段粘贴到Babel repl中,这就是我所看到的。

enter image description here

您引用的fetchUsers this似乎不是正确引用的this.state.userDataSource

希望,这有助于某种方式