android – 在React Native中从Web服务填充ListView

我有这段反应原生代码

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

let styles = require('./styles/styles');

class Sunshine extends Component {

  constructor(props) {
    super(props);
      this.state = {isLoading: true, jsonData: ''}

  }
  componentDidMount() {
    this.setState({jsonData: this.getMoviesFromApiAsync()})
  }
  render() {
    if(this.state.isLoading != true) {
      return (
        <View style={styles.container}>
        <Toolbarandroid
        style={styles.basetoolbar}
        logo={require('./ic_launcher.png')}
        title="Sunshine"
        titleTextColor="red"/>
        <View style={styles.viewcontainer}>
        <Text>{this.state.jsonData.city.id}</Text>
        <ListView
          dataSource={this.state.jsonData.list}
          renderRow={(rowData) => <Text>{rowData.dt}</Text>}
        />
        </View>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
        <Toolbarandroid
        style={styles.basetoolbar}
        logo={require('./ic_launcher.png')}
        title="Sunshine"
        titleTextColor="red"/>
        <View style={styles.singleviewcontainer}>
        <Text>Loading...</Text>
        </View>
        </View>
      );
    }

  }

  getMoviesFromApiAsync() {
      return fetch('http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=14&APPID=18dcba27e5bca83fe4ec6b8fbeed7827')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({isLoading: false, jsonData: responseJson});
          console.log(responseJson);
          return responseJson;
        })
        .catch((error) => {
          console.error(error);
        });
    }

}

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

我认为应该发生的是,当答案从服务器到达时,列表中会填充结果.但这不是正在发生的事情. Intsead我收到此错误

undefined is not an object (evaluating 'allRowIDs.length')

那么我到底做错了什么呢?

解决方法:

您必须使用数据列表创建ListViewDataSource.

constructor (props) {
  super(props)
  this.dataSource = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
  })
}

componentDidMount () {
  // You don't need to assign the return value to the state
  this.getMoviesFromApiAsync()
}

render () {
  // Use the dataSource
  const rows = this.dataSource.cloneWithRows(this.state.jsonData.list || [])
  ...
  return (
    ...
    <ListView
      dataSource={rows}
    />
  )
}

完整文档here.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...