3

我有这段 react-native 代码:

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')

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

4

1 回答 1

7

您必须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}
    />
  )
}

完整的文档在这里

于 2016-08-04T12:15:00.023 回答