singleton object in react native

前端 未结 5 1883
慢半拍i
慢半拍i 2020-12-13 08:56

I\'m new in react native.I want store multiple small small strings to common singleton object class and want to access it from singleton object for all component. Can anyone

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 09:56

    I suggest making a static class that stores data using AsyncStorage. You mentioned in a comment that you are already using AsyncStorage, but don't like spreading this functionality throughout your app. (i.e. try-catches all over the place, each component needing to check if a key is available, etc.) If this functionality were in a single class, it would clean up your code a lot.

    Another bonus to this approach is that you could swap out the implementation pretty easily, for example, you could choose to use an in-memory object or AsyncStorage or whatever and you would only have to change this one file

    NOTE: AsyncStorage is not a safe way to store sensitive information. See this question for more info on the security of AsyncStorage and alternatives.

    That said, this is how I imagine a global data holder class might look:

    export default class dataManager {
      static storeKeyValue(key, value) {
        // your choice of implementation:
        // check if key is used
        // wrap in try-catch
        // etc.
      }
    
      static getValueForKey(key) {
        // get the value out for the given key
      }
    
      // etc...
    }
    

    Then to use this class anywhere in your app, just import wherever it's needed like so:

    import dataManager from 'path/to/dataManager.js';
    
    // store value
    dataManager.storeKeyValue('myKey', 'myValue');
    
    // get value
    const storedValue = dataManager.getValueForKey('myKey');
    

    EDIT: Using Flux, Redux, or a similar technology is probably the preferred/suggested way to do this in most cases, but if you feel the Singleton pattern works best for your app then this is a good way to go. See You Might Not Need Redux

提交回复
热议问题