【问题标题】:Fetching Data From Server Using iOS Device in React Native在 React Native 中使用 iOS 设备从服务器获取数据
【发布时间】:2021-02-10 00:39:26
【问题描述】:

我刚刚开始学习 React Native 和移动设备开发。我尝试过的一件事是使用 fetch API 从http://jsonplaceholder.typicode.com/posts 获取数据 App.js 文件如下:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';

export default function App() {
    const [firstLoad, setLoad] = React.useState(true);
    const [data, upDateData] = React.useState([]);
    let isLoading = true;

    async function sampleFunc() {
        let response = await fetch("https://jsonplaceholder.typicode.com/posts");
        let body = await response.json();
        upDateData(body);
    }

    if (firstLoad) {
        sampleFunc();
        setLoad(false);
    }

    if (data.length > 0) isLoading = false;

    const posts = data.map(post => (
        <div>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
        </div>
    ));

    return (
        <View style={styles.container}>
            {isLoading ?
            <Text>Loading</Text> :
            <Text>{posts}</Text>
            }
        </View>
    );
}

这里没有什么花哨的事情,只是向服务器发出 https 请求以获取帖子。在传输数据的同时,会显示 Loading 标签,然后所有获取的帖子都会呈现在页面上。

我正在使用 Expo,当我在浏览器中运行它时一切正常,但是当我扫描 QR 码时,Expo 应用程序打开,加载消息显示几秒钟,然后应用程序崩溃。

我可能在这里做一些典型的常规 React 并且在 React Native 中没有使用的事情。奇怪的是它可以在我的电脑上运行,而不是在手机上运行。任何建议将不胜感激。提前谢谢!

【问题讨论】:

    标签: react-native fetch expo


    【解决方案1】:

    你不能在 react-native 的 Text 组件之外有文本。

    在您的示例中,在 post 函数中,您使用了 react-native 不支持的 h1p 标签。

    这里的解决方法是确保这些文本位于 Text 组件中,您可以将样式设置为那些以使它们看起来更接近您想要的。

    您可以参考docs 了解如何创建自定义样式。

    const posts = data.map(post => (
        <View>
            <Text>{post.title}</Text>
            <Text>{post.body}</Text>
        </View>
    ));
    

    如果以后要调试类似的问题,您应该会看到一个红色闪烁的屏幕,但有例外。 (可能在 Expo 上运行时没有出现)

    【讨论】:

    • 现在正在显示数据,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多