Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Desisti de tentar adaptar com Fragment

Quebrei a cabeça para tentar adaptar o código com o novo modelo inicial do React-native (usando Fragment), mas não consegui de jeito algum fazer funcionar nesse código que acessa o servidor.

Para quem estiver interessado, o código no novo modelo (com App.js do react-native e sem index para cada plataforma), mas sem fragment está funcionando assim:

index.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

App.js

import React, {Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Image,
  Dimensions,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import Post from './src/components/Post';

export default class App extends Component {
    constructor() {
      super()
      this.state = { fotos: [] }
    }
    componentDidMount() {
      fetch('https://instalura-api.herokuapp.com/api/public/fotos/rafael')
        .then(resposta => resposta.json())
        .then(json => this.setState({fotos: json}))
    }
    render() {
      return (
          <FlatList style={styles.container}
              keyExtractor={item => String(item.id)}
              data={this.state.fotos}
              renderItem={ ({item}) =>
                <Post foto={item} />
              }
          />
      );
    }
};

const styles = StyleSheet.create({
  container: {
    marginTop: 20
  },
});

Post.js

import React, { Component } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Image,
  Dimensions,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

const width = Dimensions.get('screen').width;

export default class Post extends Component {
    render() {
      return (
        <View>
          <View style={styles.cabecalho}>
            <Image source={{uri: this.props.foto.urlPerfil}}
                style={styles.fotoDePerfil}/>
            <Text>{this.props.foto.loginUsuario}</Text>
          </View>
          <Image source={{uri: this.props.foto.urlFoto}}
              style={styles.foto}/>
        </View>
      );
    }
  }

const styles = StyleSheet.create({
  cabecalho: {
    margin: 10, 
    flexDirection: 'row', 
    alignItems: 'center'
  },
  fotoDePerfil: {
    marginRight: 10, 
    borderRadius: 20, 
    width: 40, 
    height: 40
  },
  foto: {
    width: width,
    height: width
  },
})
;

O index.js e o App.js na raiz e o Post.js no src/components.

1 resposta
solução!

Só para complementar, como muito bem explicado pelo Geison nesse tópico, para o acesso local com o android não funciona localhost, tem que usar o IP 10.0.2.2:

fetch('http://10.0.2.2:8080/api/public/fotos/rafael')

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software