2017-04-19 41 views
2

代码如下, 如何在移动屏幕上显示各种属性? 我可以在控制台上看到打印出来的对象数组,但我无法使用每个对象中包含的属性来显示手机屏幕上的信息。在ListView中迭代renderRow中的对象数组,React-Native

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

您需要遍历数组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> 
); 
} 
+0

感谢您的帮助,但遗憾的是在控制台中的错误还是一样'可能未处理无极抑制(ID:0): 无法读取undefined'的特性“地图”。但是我可以在用户中看到迭代,但不能吐出模拟器上的属性 –

0

我不能评论上一个答案,但它应该工作。如果它给了你上面发布的错误信息,说明它为Cannot read property 'map' of undefined这表明你传递给renderRowuser参数不是一个数组或它是空的或者它有问题。专注于解决这一部分。

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

enter image description here

它看起来像this你引用的this.state.userDataSource不正确this被引用。

希望这有助于在某种程度上