【问题标题】:There is way to save only part of the string object into async-storage?有办法只将部分字符串对象保存到异步存储中吗?
【发布时间】:2020-07-01 22:09:24
【问题描述】:
有没有办法只将部分字符串对象保存到异步存储中?
例如,如果在“result.userPrincipalName”中保存“bob23@hotmail.com”
所以我希望它只保存“bob23”,那么该怎么做呢?
await AsyncStorage.setItem(
'AZURE-USERNAME',
JSON.stringify(
result.userPrincipalName.substring(0, data.indexOf('@'))
)
);
【问题讨论】:
标签:
javascript
reactjs
react-native
async-await
【解决方案1】:
你会做这样的事情。
您可以在某个字符之后删除部分字符串。
正如我在文档中看到的那样。它存储为键值对。
所以我做了修改
let data = JSON.stringify(result.userPrincipalName);
//here substring will remove characters after and including `@`
data = data.substring(0, data.indexOf('@'));
await AsyncStorage.setItem('AZURE-USERNAME', data);
【解决方案2】:
我相信您需要在顶层处理您想要的数据(将新输入添加到用户/数据库中的新字段以及想要的数据等。我不知道您从哪里得到您的userPrincipalName)。
但是,如果不可能,您可以按照以下方式进行操作:
const name = result.userPrincipalName.split('@')[0];
if (!name) throw new Error('Invalid email');
await AsyncStorage.setItem('AZURE-USERNAME', name);
【解决方案3】:
您只需在 Javascript 中使用 split 函数即可。 More information
//Split the mame using split function
const splitName = result.userPrincipalName.split("@");
//Get the split value and save it
//After you splitting [0] mean first character set
const name = splitName[0];
//Save it to AsyncStorage
await AsyncStorage.setItem("AZURE-USERNAME", JSON.stringify(name));