Expo SecureStore 认证后保存userId和token 后续仅可读取token问题
问题根因
SecureStore.setItemAsync仅支持字符串类型的存储值,接口返回的userId为数字类型,直接传入会导致存储异常。- 你没有为异步存储方法添加
await关键字,存储操作未完成就触发了页面跳转,出现了token已写入、userId还未写入的时序问题。
修复方案
调整登录逻辑代码,将userId转为字符串后存储,同时等待存储操作全部完成后再跳转页面,修改后代码如下:
const doUserLogIn = async() => { try { const response = await fetch('http://someurl-dev.de/api/login/?email='+email+'&password='+password, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }); const json = await response.json(); // 等待存储完成,同时将数字类型userId转为字符串 await SecureStore.setItemAsync('userid', String(json.userId)); await SecureStore.setItemAsync('token', json.token); } catch (e) { alert('Error1:'+e); } finally { try{ navigation.navigate('Schichten'); } catch(e) {alert('Error2:'+e); } } }
读取注意事项
后续读取userId时如果需要使用数字类型,将读取到的字符串转回数字即可:
const userId = Number(await SecureStore.getItemAsync('userid'))
内容的提问来源于stack exchange,提问作者Ankit Vij
相关产品推荐
相关产品推荐

