React-Native fetch by Tutorial Facebook返回错误

时间:2017-06-12 17:20:10

标签: android ios json facebook react-native

React-Native fetch by Tutorial Facebook返回错误

null错误不是对象(评估' this.state.datasource')

我如何处理我的代码

class ModuleRecView extends Component {
    componentWillMount() {

      return fetch('https://facebook.github.io/react-native/movies.json')
         .then((response) => response.json())
         .then((responseJson) => {
           let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
           this.setState({
             isLoading: false,
             dataSource: ds.cloneWithRows(responseJson.movies),
           }, function() {
             // do something with new state
           });
         })
         .catch((error) => {
           console.error(error);
         });

    }
    render() {

      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
          />
        </View>
      );
    }
}

export default ModuleRecView;

3 个答案:

答案 0 :(得分:1)

我认为问题在于此链接https://facebook.github.io/react-native/movies.json它返回404页面未找到。您可以尝试使用其他json链接或在此处找到所需的数据https://github.com/facebook/react-native/blob/master/website/src/react-native/movies.json

答案 1 :(得分:0)

componentWillMount之上:

constructor() {
  super();
  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  this.state = {
    dataSource: ds.cloneWithRows([]),
  };
}

答案 2 :(得分:0)

我通常这样做:

import React, { Component } from 'react'
import { ListView, View, Text } from 'react-native'

class ModuleRecView extends Component {
  state = {
    datasource: new ListView.DataSource({rowHasChanged: (r1, r2) => r2 !== r2}),
    isLoading: true
  }

  componentWillMount() {
    fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
       this.setState({
         isLoading: false,
         dataSource: this.state.datasource.cloneWithRows(responseJson.movies),
       }, () => {
         // do something with new state
       });
    })
    .catch((error) => {
      console.error(error);
    });
  }

  render() {
    return (
      <View style={{flex: 1, paddingTop: 20}}>
        <ListView
          dataSource={this.state.datasource}
          renderRow={(rowData) => <Text>{rowData.title}, {rowData.releaseYear}</Text>}
        />
      </View>
    );
  }
}

export default ModuleRecView;

请注意,RN现在有一个名为&lt; this answer /&gt;的新组件。这与<ListView/>组件相同,但要好得多。