【问题标题】:Iterate an array of objects within renderRow in ListView, React-Native在ListView,React-Native中迭代renderRow中的对象数组
【发布时间】:2017-09-15 12:42:05
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢帮助,可惜控制台中的错误还是一样Possible Unhandled Promise Rejection (id: 0): Cannot read property 'map' of undefined。但是我可以在用户中看到迭代,但不能在模拟器上吐出属性
    【解决方案2】:

    我无法评论上一个答案,但它应该可以。如果它给您上面发布的错误,上面写着Cannot read property 'map' of undefined,这表明您传递给renderRowuser 参数不是数组,也不是空的,或者有问题。专注于解决那部分。

    我将 fetchUsers 函数的代码 sn-p 粘贴到 Babel repl 中,这就是我看到的。

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

    希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2018-03-23
      • 1970-01-01
      • 2017-07-24
      • 2020-10-05
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多