我是React Native的新手,我想在我的專案中應用AsyncStorage。我正在做一個專案,我可以在平面串列中添加教室,然后在每個教室中,我可以使用平面串列添加每個班級的學生名字。Asyncstorage將同時應用于教室串列和學生串列。
我的期望是,我添加了教室A、教室B和教室C,然后當我按下教室A時,我可以添加學生的名字,而當我去教室B時,名字串列仍然是空的,等待我去填充串列。
我的實際結果是,當我在教室A中添加學生A、學生B、學生C后,當我去教室B時,教室A中的3名學生在教室B的名單中仍然可用。
所以,我怎樣才能解決這個問題以滿足我的要求,如果你能提供一個帶有解釋的代碼,那將是非常有幫助的,非常感謝。非常感謝您的幫助
這是我的代碼。
這是我在MainMenu.js中需要添加教室的代碼。
import React, { useState , useEffect } from 'react;
import {
View,
Text,
TouchableOpacity,
FlatList。
Alert,
TextInput。
StyleSheet,
} from 'react-native'/span>。
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage'/span>;
import { useNavigation } from '@react-navigation/native'。
import { CardStyleInterpolators } from '@react-navigation/stack'。
export default function MainMenu() {
const [classroomInput, setClassroomInput] = useState('') 。
const [classroom, setClassroom] = useState([] )。
const navigation = useNavigation();
useEffect(() => {
getClassroom()。
}, []);
useEffect(() => {
saveClassroom(classroom)。
}, [classroom])。
const saveClassroom = async(classroom) => {
try {
const stringifyClassroom = JSON.stringify(classroom)。
await AsyncStorage.setItem('classroom', stringifyClassroom) 。
} catch(錯誤) {
console.log(錯誤)。
}
};
const getClassroom = async ( ) => {
try {
const classrooms = await AsyncStorage.getItem('classroom')。
if (classrooms !== null) {
setClassroom(JSON.parse(classrooms)) 。
}
} catch(錯誤) {
console.log(錯誤)。
}
};
const addClassroom = (/span>) => {
if (classroomInput === ''/span>){
Alert.alert('Error', '請輸入class')。
} else {
const newClassroom = {
id: Math.random().toString() 。
Classroom: classroomInput,
};
setClassroom([...classroom,newClassroom])。
setClassroomInput(''/span>)。
}
};
const deleteClassroom = (classroomId)=> {
const newClassrooms = classroom.filter(item => item.id !== classroomId) 。
setClassroom(newClassrooms)。
};
return (
<View style={styles.container}> /span>
<TextInput。
style={styles.input}。
placeholder={'Add Classrooms'}。
value={classroomInput}'}。
onChangeText={(text) => setClassroomInput(text)}。
/>
<TouchableOpacity onPress={() => addClassroom()} style={styles.button}>
<Text>添加教室</Text>
</TouchableOpacity>/span>
<FlatList
style={styles.flatlist}。
data={classroom}
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<TouchableOpacity onPress= {() => navigate('Classroom', item)} >
<View style={styles.listItem}>
<View>/span>
<Text>/span>
{item?.Classroom}
</Text> {item?
</View>/span>
<View >
<TouchableOpacity style={[style.delete] } onPress={() => deleteClassroom(item?.id)}>
< Icon name="remove" size={15} color={'#fff'}。/>
</TouchableOpacity>
</View>/span>
</View>/span>
</TouchableOpacity>/span>
)}
/>
</View>>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%'。
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue'。
padding: 10,
marginBottom: 10,
},
delete: {
backgroundColor: '#ff3333'。
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
});
這是Classroom.js,我將在這里添加學生名單
。import React, { useState , useEffect } from 'react;
import {
View,
Text,
TouchableOpacity,
FlatList。
Alert,
TextInput。
StyleSheet,
} from 'react-native'/span>。
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage'/span>;
import { useRoute } from '@react-navigation/core'。
const Classroom = ( {navigation}) => {
const [studentInput, setStudentInput] = useState('') 。
const [student, setStudent] = useState([] )。
const route = useRoute();
useEffect(() => {
getStudent()。
}, []);
useEffect(() => {
saveStudent(學生)。
}, [student])。
const saveStudent = async (student) => {
try {
const stringifyStudent = JSON.stringify(學生)。
await AsyncStorage.setItem('student', stringifyStudent)。
} catch(錯誤) {
console.log(錯誤)。
}
};
const getStudent = async ( ) => {
try {
const students = await AsyncStorage.getItem('student')。
if (students !== null) {
setStudent(JSON.parse(students))。
}
} catch(錯誤) {
console.log(錯誤)。
}
};
const addStudent = (/span>) => {
if (studentInput === ''/span>){
Alert.alert('錯誤', '請輸入學生姓名')。
} else {
const newStudent = {
id: Math.random().toString() 。
Name: studentInput,
};
setStudent([...student,newStudent])。
setStudentInput(''/span>)。
}
};
const deleteStudent = (studentId) => {
const newStudent = student.filter(item => item.id !== studentId) 。
setStudent(newStudent)。
};
return (
<View styles={styles.container}> /span>
<TouchableOpacity onPress={()/span>=> navigation.goBack()} style={styles.button}>
<Text>Back</Text>
</TouchableOpacity>/span>
<Text style={{fontWeight: 'bold', fontSize: 20}}> {route. params.Classroom}</Text>。
<TextInput。
style={styles.input}。
placeholder={'Add Student Name'}。
value={studentInput}。
onChangeText={(text) => setStudentInput(text)}。
/>
<TouchableOpacity onPress={()=> addStudent()} style={styles.button}>
<Text>添加學生</Text>
</TouchableOpacity>/span>
<FlatList
style={styles.flatlist}。
data={student}>
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<View style={styles.listItem}>
<View>/span>
<Text style={{style. classText , {fontSize: 18}]}>
{item?.Name}
</Text> {item?
</View>/span>
<View >
<TouchableOpacity style={[style.delete] } onPress={() => deleteStudent(item?.id)}>
< Icon name="remove" size={15} color={'#fff'}。/>
</TouchableOpacity>
</View>/span>
</View>/span>
)}
/>
</View>>
);
};
export default Classroom;
const styles = StyleSheet.create( {
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%'。
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue'。
padding: 10,
marginBottom: 10,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
delete: {
backgroundColor: '#ff3333'。
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
});
uj5u.com熱心網友回復:
你的問題是你在用同一個鍵student來設定所有的學生。
你需要做的是,如果你的班級名稱是唯一的,就使用班級名稱為你的存盤設定一個動態鍵,否則你需要使用類似uuid的東西,以便為你的班級創建唯一的id.
。例如,你可以在保存學生的函式中這樣做
const saveStudent = async (student)=> {
try {
const stringifyStudent = JSON.stringify(學生)。
await AsyncStorage。 setItem(`class${class.name}: students`, stringifyStudent) 。
} catch(錯誤) {
console.log(錯誤)。
}
};
并對你的get student函式這樣做
const getStudent = async()=> {
try {
const students = await AsyncStorage. getItem(`class${class.name}:students`) 。
if (students !== null) {
setStudent(JSON.parse(students))。
}
} catch(錯誤) {
console.log(錯誤)。
}
};
也可以嘗試使用uuid包而不是Math.random來創建你的id。的確,使用Math.random獲得相同數字的可能性很小,但仍有可能,但使用uuid則不可能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/326345.html
標籤:
