2017-04-19 143 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被引用。

希望這有助於在某種程度上