React-Native中fetch本地json文件

写作时间:2020/4/26
React-Native版本:0.62
开发平台:windows
目标平台:android

如果你想了解如何利用fetch获取网络数据,可以查看这篇文章
React-Native使用FlatList组件实现上拉加载功能

在开发项目的过程中,很多时候需要我们自行模拟后台数据。本文通过一个具体的RN项目来展示如何fetch本地的json文件,尽可能地模拟获取真实网络数据。

首先新建一个RN项目,将以下代码替代App.js中的内容

// App.js
import React from 'react';
import {Text, View} from 'react-native';

export default class App extends React.Component {
    constructor() {
        super();
        this.state = {id: '', key: ''};
    }

    componentDidMount() {
        fetch('http://localhost:8081/src.json')
            .then(response => {
                return response.json();
            })
            .then(responseJson => {
                this.setState({
                    id: responseJson.id,
                    key: responseJson.key,
                });
            })
            .catch(error => {
                console.error(error);
            });
    }

    render() {
        return (
            <View>
                <Text>
                    {this.state.id}, {this.state.key}
                </Text>
            </View>
        );
    }
}

从以上代码可以看出,fetch获取的是名为src.json的文件,接下来,在和App.js相同的路径下创建src.json文件,内容如下

// src.json
{"id":"dataid","key":"datakey"}

以上工作完成之后,运行代码即可。需要注意的是,如果你需要设置很多json文件的话,你可以对这些文件进行整理,放入你指定的文件夹中,相应的,fetch的路径也需要进行修改。


版权声明:本文为weixin_42405831原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。