2017-01-24 5 views
0

React NativeのAPIにデータを使用して複数のビューを作成しようとしています。Webサービス/ APIからのデータをビューに取り込み

私は以下のコードを使用しているが、私はこのエラーを保つように、ページは、Webサービス応答の前にレンダリング:

未処理JS例外:ヌル(「this.state.user.map」を評価)オブジェクトではありません

export default class Component6 extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     user: null 
    } 
} 
componentDidMount() { 
    this.fetchUsers(); 
} 

fetchUsers() { 
    fetch('https://jsonplaceholder.typicode.com/users') 
     .then((response) => response.json()) 
     .then((response) => { 

      this.setState({ 

      }); 
     }); 
} 



render() { 
    contents = this.state.user.map(function (item) { 
     return (
      <View key={item.id} style={styles.content}> 
       <Text>{item.email}</Text> 
      </View> 
     ); 
    }); 
    return (
      {contents} 
    ); 
} 
} 
AppRegistry.registerComponent('Component6',() => Component6); 

答えて

0

あなたがレンダリングの外にあなたの内容を移動するには「もし」ステートメントを提供し、また、そのより良いことができますので、それはすべての上でそれを再定義ではないですが、レンダリング:

export default class Component6 extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     user: null 
    } 
} 
componentDidMount() { 
    this.fetchUsers(); 
} 

fetchUsers() { 
    fetch('https://jsonplaceholder.typicode.com/users') 
     .then((response) => response.json()) 
     .then((response) => { 
      item = this.viewconstur(response), 

      this.setState({ 
       user: item 
      }); 
     }); 
} 

    renderContents =() => { 
    if (this.state.user) { 
     this.state.user.map((item) => (
     <View key={item.id} style={styles.content}> 
      <Text>{item.email}</Text> 
     </View> 
    )); 
    } 
    } 

render() { 
    return (
      <View> 
      {this.renderContents()} 
      </View> 
    ); 
} 
} 
+0

おかげで、私はもはやERROを取得していません上記のrですが、ビューは空白です – John

+0

フェッチが成功した場合のみビューが表示されます。また、fetchUsersを編集してthis.setStateに正しい情報を提供する必要があります。 –

関連する問題