【问题标题】:React-native: how to get JSON from backend and put the objects in react-native elements, such as Text?React-native:如何从后端获取 JSON 并将对象放入 react-native 元素中,例如 Text?
【发布时间】:2018-12-26 20:28:54
【问题描述】:

我正在尝试从 php 文件中获取 JSON 数据,这似乎工作正常;我可以提醒来自 JSON 的值。但我希望能够将这些值放在移动应用程序屏幕上的文本元素或其他内容中。我希望在屏幕打开时发生这种情况,而不是在按下按钮时发生。因此,我创建了一个获取 JSON 的函数,并尝试在 Text 元素中返回一个值。从渲染中调用此函数。我没有收到错误消息,但它不起作用。什么都没有显示。

代码如下:

import React, { Component } from 'react';
import { View, Text, AsyncStorage, Alert } from 'react-native';
import { UsersMap } from '../UsersMap';
import { PrimaryButton } from '../Buttons';
import styles from './styles';

class RestOptions extends Component {

    getSearchResults() {
        fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
        .then((response) => response.json())
        .then((responseJson) => {
            var JSON_Test = responseJson["distance"][0];
            //Alert.alert(JSON_Test);
            return (
                <View>
                    <Text>{JSON_Test}</Text>
                </View>
            );
        }).catch((error) => {
            console.error(error);
        });
    }

    setReservation = () => {
        this.props.navigation.navigate('SetReservation');
    };

    render() {
        return (
            <View>
                <UsersMap />
                {this.getSearchResults()}
                <PrimaryButton
                    label="Set Reservation"
                    onPress={() => this.setReservation()}
                />
            </View>
        );
    }
};

export default RestOptions;

这就是发生的事情。 JSON 值应该出现在地图和按钮之间:

Search Results Screen

【问题讨论】:

    标签: json react-native fetch


    【解决方案1】:

    首先,为了在屏幕打开时获取数据,您应该使用生命周期方法componentWillMount,它在第一次渲染之前执行,然后将结果存储在组件的状态中。 React docs on state and lifecycle

    class RestOptions extends Component {
        constructor(props) {
            super(props);
            this.state = {
                jsonTest: null
            }
        }
    
        componentWillMount() {
            this.getSearchResults();
        }
    
        getSearchResults() {
            fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
            .then((response) => response.json())
            .then((responseJson) => {
                var JSON_Test = responseJson["distance"][0];
                //Alert.alert(JSON_Test);
                this.setState({ jsonTest: JSON_Test });
            }).catch((error) => {
                console.error(error);
            });
        }
    //...
    

    然后就可以在render()方法上显示值了:

    render() {
        return (
            <View>
                <UsersMap />
    
                <Text>{this.state.jsonTest}</Text>
    
                <PrimaryButton
                    label="Set Reservation"
                    onPress={() => this.setReservation()}
                />
            </View>
        );
    }
    

    如果响应是一个值数组,您可以使用map() 将每个值显示在各自的Text 元素中:

    {this.state.jsonTest.map((value, index) => <Text key={index}>{value}</Text>)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-07
      • 2017-08-11
      • 2019-01-07
      • 2015-07-15
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多