且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将本机iOS应用程序的数据迁移到React Native应用程序的异步存储

更新时间:2022-03-31 01:09:26

我们最近在其中一个应用中使用了相同的用例,并决定执行以下操作:

We have recently had the same use-case in one of our apps and decided to do the following:

像通常一样从NSUserDictionary读取(获取所有元素)并将它们传递给RCTRootView

Read from NSUserDictionary just like normally (fetch all the elements) and pass them to RCTRootView

NSDictionary *userSettings = @{}; // fetch them here
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"XYZ"
                                               initialProperties:userSettings
                                                 launchOptions:launchOptions];

假设您的userSettings词典包含例如accessToken属性,您应该能够从根React组件(传递给AppRegistry.registerComponent的组件)内部访问this.props.accessToken.

Assuming your userSettings dictionary contains e.g. accessToken property, you should be able to just access this.props.accessToken from within your root React component (the one you pass to AppRegistry.registerComponent).

接下来,您可以检查值是否已经持久保存到AsyncStorage(或者是否应该使用任何其他的userSettings副本),如果不是,则保存当前值.

Next, you can either check if values have been already persisted to AsyncStorage (or is there any other copy of userSettings that you should use) and if not - persist the current values.

另一种替代方法是使用React Native中可用的Settings模块,该模块允许您访问NSUserDefaults.它具有.get().set()方法,因此从技术上讲应该可以使用它.

Another alternative is to use Settings module that is available in React Native that allows you to access NSUserDefaults. It has .get() and .set() methods, so technically it should be possible to use it.

请注意,直到您从Xcode内部重新运行应用程序之后,通过initialProperties传递的userSettings才会更新.

Note that userSettings passed through initialProperties will not update until you re-run the app from within the Xcode.