Sim*_*ris 6 local-storage cordova react-native
我正在迁移 Cordova 应用程序以对本机做出反应,并且在我们更新应用程序时需要访问 localstorage 以保持登录状态。
我如何在更新版本的应用程序中从旧应用程序访问 window.localStorage?
我正在使用 react-native 0.60.5 我有异步存储,但这没有显示我需要/应该拥有的密钥。
我试图安装这个包,但我不确定它是否与最新版本的 react native 兼容。
https://www.npmjs.com/package/react-native-webkit-localstorage-reader
执行完所有步骤后,我收到构建错误。
/react-native/React/Base/RCTBridgeModule.h:10:9: 'React/RCTDefines.h' 文件未找到
我也一直在努力解决这个问题,对我来说有效的是:
在加载任何应用程序之前,我将检查旧数据存储是否已迁移(RN LocalStorage 值 f.ex: WEBVIEW_LOCAL_STORAGE_MIGRATED),如果没有,我将显示一个 WebView 屏幕,该屏幕本身有一个注入 JS 代码来获取 localStorage 并将其发送到React Native 代码,我可以在其中使用它。
我正在使用react-native-webview
这是代码
const INJECTED_JAVASCRIPT = `(function() {
window.ReactNativeWebView.postMessage(JSON.stringify(window?.localStorage || null));
})();`;
Run Code Online (Sandbox Code Playgroud)
// Not required just to show something is happening
const customHTML = `
<body style="background: #FCAD97">
<div style="display: flex;flex-direction: row;align-items: center;justify-content: center;height: 100%;">
<h1 style="text-align: center; margin-top: 20px;font-size: 3rem;font-family: Arial, sans-serif;display: table;color:white;">Syncing user data, please wait...</h1>
</div>
</body>`;
Run Code Online (Sandbox Code Playgroud)
function handleOnMessage(event) {
// This will get the local storage in format {"localStorageKey": "localStorageValue"}
const message = JSON.parse(event.nativeEvent.data);
// Do something with the old local storage
}
Run Code Online (Sandbox Code Playgroud)
return (
<WebView
originWhitelist={['*']}
source={{ html: customHTML, baseUrl: 'app://localhost' }}
javaScriptEnabled={true}
injectedJavaScript={INJECTED_JAVASCRIPT}
onMessage={handleOnMessage}
/>
);
Run Code Online (Sandbox Code Playgroud)
全部完成后,您可以使用迁移的 localStorage 数据继续使用应用程序。
整个代码如下所示:
const INJECTED_JAVASCRIPT = `(function() {
window.ReactNativeWebView.postMessage(JSON.stringify(window?.localStorage || null));
})();`;
const customHTML = `
<body style="background: #FCAD97">
<div style="display: flex;flex-direction: row;align-items: center;justify-content: center;height: 100%;">
<h1 style="text-align: center; margin-top: 20px;font-size: 3rem;font-family: Arial, sans-serif;display: table;color:white;">Syncing user data, please wait...</h1>
</div>
</body>`;
function handleOnMessage(event) {
// This will get the local storage in format {"localStorageKey": "localStorageValue"}
const message = JSON.parse(event.nativeEvent.data);
// Do something with the old local storage
}
return (
<WebView
originWhitelist={['*']}
source={{ html: customHTML, baseUrl: 'app://localhost' }}
javaScriptEnabled={true}
injectedJavaScript={INJECTED_JAVASCRIPT}
onMessage={handleOnMessage}
/>
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
142 次 |
最近记录: |