【发布时间】:2021-12-13 23:19:12
【问题描述】:
在 React Native 中,我希望每次在文本框中键入时都使用唯一 id 存储对象数组数据。我正在使用异步存储,但不知道如何处理。
【问题讨论】:
标签: javascript android ios react-native
在 React Native 中,我希望每次在文本框中键入时都使用唯一 id 存储对象数组数据。我正在使用异步存储,但不知道如何处理。
【问题讨论】:
标签: javascript android ios react-native
你可以实现这样的东西
第一次运行
npm i @react-native-async-storage/async-storage
然后创建一个 AsyncStore.js 或类似文件:
import AsyncStorage from '@react-native-async-storage/async-storage';
export const storeObject = async (object) => {
const id = await createId()
const identified = {...object, id }
const jsonValue = JSON.stringify(identified);
await AsyncStorage.setItem('@object-' + id, jsonValue);
};
export const getObject = async (id) => {
const storedObject = await AsyncStorage.getItem('@object-' + id);
if (storedObject){
return JSON.parse(storedObject );
}
};
export const storeIds = async (ids) => {
const jsonValue = JSON.stringify(ids);
await AsyncStorage.setItem('@object-ids', jsonValue);
};
export const getIds = async (id, ids) => {
const storedIds = await AsyncStorage.getItem('@object-ids');
if (storedIds) {
return JSON.parse(storedIds );
}
};
const createId = async() => {
const ids = await getIds();
const id = Math.max(ids) + 1
await storeIds([...ids,id])
return id;
}
编辑:我添加了一些未经测试的唯一标识符代码
【讨论】: