How to fetch data from local JSON file on react native?

自闭症网瘾萝莉.ら 提交于 2019-11-26 19:06:58

问题


How can I store local files such as JSON and then fetch the data from controller?


回答1:


Since React Native 0.4.3 you can read your local JSON file like this:

const customData = require('./customData.json');

and then access customData like a normal JS object.




回答2:


ES6/ES2015 version:

import customData from './customData.json';



回答3:


For ES6/ES2015 you can import directly like:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

If you use typescript, you may declare json module like:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}



回答4:


Use this

import data from './customData.json';



回答5:


maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...




回答6:


Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.



来源:https://stackoverflow.com/questions/29452822/how-to-fetch-data-from-local-json-file-on-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!