React Native通过导航响应在api中发出请求

时间:2019-03-05 18:37:41

标签: reactjs react-native react-router react-native-navigation

Main.js

import React, { Component } from 'react';
import api from '../service/api';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';

export default class Main extends Component {
    static navigationOptions = {
        title: 'JSHunt',
    };

    state = {
        lista: [],
    };

    componentDidMount() {
        this.loadProducts();
    }

    loadProducts = async () => {
        const response = await api.get("/tarefa/");
        const { lista } = response.data;
        this.setState({ lista });
    };

    renderItem = ({ item }) => (
        <View style={styles.listaContainer}>     
            <Text style={styles.listaDescription}>{item}</Text>
            <TouchableOpacity style={styles.listaButton} onPress={() => {
                this.props.navigation.navigate("Tarefa", { tarefa: item});
            }}>
                <Text style={styles.textButton}>Acessar</Text>
            </TouchableOpacity>
        </View>
    );

    render() {
        return (
            <View style={styles.listaContainer}>     
                <FlatList
                    contentContainerStyle={styles.list}   
                    data={this.state.lista}
                    keyExtractor={item =>item}
                    renderItem = {this.renderItem}
                />
            </View>
        );
    }
}

Tarefa.js

import React from 'react';

import { Text} from 'react-native';

const Tarefa = ({navigation }) => {    
    console.log(navigation.state.params.tarefa);
    return (
        <Text>{navigation.state.params.tarefa}</Text>
    );   
};


export default Tarefa;

主要,我向API发出请求,该API返回一个列表,当我单击列表中的一个值时,它会转到一个新的屏幕,该屏幕是任务的eh,我需要使用该值一个新请求,将是type detail。

但是我无法发出新请求,我只能在“ navigation.state.params.tarefa”中显示应为新请求调用的值

例如会留下

http://localhost:8080/tarefa/navigation.state.params.tarefa

或出现在屏幕上

http://localhost:8080/tarefa/1



Main.JS
http://localhost:8080/tarefa/
    {"lista":["1","2","3","4"]}



Tarefa.js
    http://localhost:8080/tarefa/1
    {"id":"1","city":"teste"}

Main.js我已经完成了数组中的所有列表“ lista”。在“ Tarefa.js”中,我应该列出您的详细信息。但是我不知道如何通过导航再次访问api

0 个答案:

没有答案