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

后端 未结 7 1575
执念已碎
执念已碎 2020-12-02 10:12

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

相关标签:
7条回答
  • 2020-12-02 10:47

    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.

    0 讨论(0)
  • 2020-12-02 10:53

    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...

    0 讨论(0)
  • 2020-12-02 10:56

    ES6/ES2015 version:

    import customData from './customData.json';
    
    0 讨论(0)
  • 2020-12-02 10:56

    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.

    0 讨论(0)
  • 2020-12-02 11:02

    The following ways to fetch local JSON file-

    ES6 version:

    import customData from './customData.json'; or import customData from './customData';

    If it's inside .js file instead of .json then import like -

    import { customData } from './customData';
    

    for more clarification/understanding refer example - Live working demo

    0 讨论(0)
  • 2020-12-02 11:07

    Use this

    import data from './customData.json';
    
    0 讨论(0)
提交回复
热议问题