2016-11-21 14 views
1

私はReact Nativeを初めて使用し、提供されたFetch APIを適切に利用する方法を混乱させています。Reactネイティブコンポーネントの取得呼び出しを行うタイミング

コール自体(ここで概要を説明したように:http://facebook.github.io/react-native/docs/network.html)は簡単ですが、正常な応答をログアウトすることはできますが、データをレンダリングする時間が来ると未定義です。

空の 'movies'配列を定義し、componentDidMount()から 'setState'を呼び出して置き換えて、再レンダリングをトリガーすると思います。この仮定は間違っていますか?

次のエラーで結果以下のコードサンプル:任意の助けを事前に

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

ありがとう!

あなたが ListView.DataSourceにデータを配置する必要があるためです
import React, { Component } from 'react'; 
import { AppRegistry, ListView, Text, View } from 'react-native'; 

class ReactNativePlayground extends Component { 

    constructor() { 
     super(); 
     this.state = { 
     movies: [] 
     } 
    } 

    componentDidMount() { 
     fetch('https://facebook.github.io/react-native/movies.json') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
     this.setState({ 
      movies: responseJson.movies 
     }) 
     }) 
     .catch((error) => { 
     console.error(error); 
     }); 
    } 

    render() { 
     return (
     <View> 
      <Text>test</Text> 
      <ListView 
       dataSource={this.state.movies} 
       renderRow={(row) => <Text>{row.title}</Text>} 
      /> 
     </View> 
    ) 
    } 
} 

AppRegistry.registerComponent('ReactNativePlayground',() => ReactNativePlayground); 
+0

'this.state.movi​​es '' render'メソッドの 'return'ステートメントの前に' '' 'メソッドを呼び出すかどうかを確認してください配列やオブジェクトを記録するかどうかを確認してください –

答えて

2

constructor (props) { 
    super(props); 

    const ds = new ListView.DataSource({ 
    rowHasChanged: (a, b) => a !== b 
    }) 

    this.state = { 
    movies: ds.cloneWithRows([]) 
    } 
} 

// Inside the response JSON: 

this.setState({ 
    movies: this.state.movies.cloneWithRows(responseJson.movies) 
}); 

React Native ListView docsは、セットアップのこの種を示しています。データソースを使用すると、データのリストをレンダリングするときに最適化が行われます(たとえば、rowHasChangedの機能に気付くと、データが変更されていないときに行が不必要に再描画されるのを防ぎます)。

+0

あなたは聖人です。上記の構文を使用して私が逃したものです。ありがとう! –

関連する問題