我正在训练react-native。我想知道如何在本地保存数据。
我有一个待办事项列表,并选择分配给这个任务的人。
我想保存我添加的任务,以便在我停止和重新启动应用程序时保留它们。我正在考虑使用异步存储,所以我这样做:
const storeData = async (task) =>{尝试{等待AsyncStorage。setItem("关键",任务)} catch (e) {//错误}}
但它似乎不工作。
这是我这个页面的所有代码。你能帮我让我的代码工作,并向我解释这个函数在这个过程中的行为吗?
谢谢。
import React, {useState} from 'react';
import { KeyboardAvoidingView, Text, View, TextInput, TouchableOpacity, Keyboard, ScrollView } from 'react-native';
import Task from '../../Task';
import SelectDropdown from 'react-native-select-dropdown'
import styles from "../../../assets/styles"
export default function Trucs() {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
const users = ["Jibé", "Charly"]
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const storeData = async (task) => {
try {
await AsyncStorage.setItem('key', task)
} catch (e) {
// lance une erreur
}
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy)
storeData(task)
}
return (
<View style={styles.wrap}>
{/* Added this scroll view to enable scrolling when list gets longer than the page */}
<ScrollView
contentContainerStyle={{
flexGrow: 1
}}
keyboardShouldPersistTaps='handled'
>
{/* Today's Tasks */}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Trucs à faire</Text>
{/* This is where the tasks will go! */}
{
taskItems.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<View>
<Task text={item}/>
<SelectDropdown
data={users}
onSelect={(selectedItem, index) => {
console.log(selectedItem, index)
}}
buttonTextAfterSelection={(selectedItem, index) => {
// text represented after item is selected
// if data array is an array of objects then return selectedItem.property to render after item is selected
return selectedItem
}}
rowTextForSelection={(item, index) => {
// text represented for each item in dropdown
// if data array is an array of objects then return item.property to represent item in dropdown
return item
}}/>
</View>
</TouchableOpacity>
)
})
}
</View>
</ScrollView>
{/* Write a task */}
{/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
<KeyboardAvoidingView
// behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.writeTaskWrapper}
>
<TextInput style={styles.input} placeholder={'Rajouter un truc à faire'} value={task} onChangeText={text => setTask(text)} />
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrapper}>
<Text style={styles.addText}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
我觉得你没有得到你存储在AsyncStorage正确的数据。看看我的两个函数,它们通过键来存储和检索数据。
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
const getData = async (key) => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};
你可以调用getData("yourKey")来获取存储的元素。
这里有几点:
1- AsyncStorage.setItem()接受一个键和一个值,它们都是string。所以你需要在storeData方法
中添加await AsyncStorage.setItem('key', JSON.stringify(task))
2-你需要在组件挂载后读取数据,并使用useEffect之类的东西将其放入你的状态中,以便在重新启动应用程序时显示。
useEffect(() => {
AsyncStorage.getItem('key').then((res) => {
setTask(JSON.parse(res));
})
} , [])