如何在本机反应上从本地 JSON 文件中获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29452822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch data from local JSON file on react native?
提问by mrded
How can I store local files such as JSON and then fetch the data from controller?
如何存储本地文件(例如 JSON),然后从控制器获取数据?
回答by peter
Since React Native 0.4.3 you can read your local JSON file like this:
从 React Native 0.4.3 开始,您可以像这样读取本地 JSON 文件:
const customData = require('./customData.json');
and then access customData like a normal JS object.
然后像访问普通的 JS 对象一样访问 customData。
回答by PaulMest
ES6/ES2015 version:
ES6/ES2015 版本:
import customData from './customData.json';
回答by Little Roys
For ES6/ES2015 you can importdirectly like:
对于 ES6/ES2015,您可以直接导入,如:
// 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:
如果您使用打字稿,您可以像这样声明 json 模块:
// tying.d.ts
declare module "*.json" {
const value: any;
export default value;
}
回答by Mudassir Zakaria
Use this
用这个
import data from './customData.json';
回答by clagccs
maybe you could use AsyncStoragesetItemand getItem...and store the data as string, then use the json parserfor convert it again to json...
也许您可以使用AsyncStorage setItem和getItem...并将数据存储为字符串,然后使用json 解析器将其再次转换为 json ...
回答by Colin Ramsay
Take a look at this Github issue:
看看这个 Github 问题:
https://github.com/facebook/react-native/issues/231
https://github.com/facebook/react-native/issues/231
They are trying to requirenon-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.
他们正在尝试require非 JSON 文件,尤其是 JSON。目前没有这样做的方法,所以你要么必须像@CocoOS 提到的那样使用 AsyncStorage,要么你可以编写一个小的本机模块来做你需要做的事情。

