英文:
React Native async storage problem. It does only load the item before
问题
我正在编写一个React Native应用程序,用于计算成绩的平均值。您可以在其中创建科目,并为每个科目添加成绩。为此,我有不同的屏幕。我将它保存在一个字典中,然后将其加载到异步存储中。例如:
{subject 1: [grades], subject 2: [grades] }。在实际生活中:{math: [1, 4,2], english:[5,2]}。
但现在我遇到了一个问题,当我添加一个科目时,它会在加载之前加载该科目,然后当我添加一个新科目时,它才会加载。
这里是一个展示问题和完整代码的视频(两个链接是相同的):https://www.dropbox.com/s/4yqzl22zannb9ln/reactnativeproblem.mp4?dl=0 https://drive.google.com/file/d/1Wi37lmMCgYOAFQSOMOQebCWkQSsFiPaz/view?usp=sharing
以下是app.js的代码:
import { React, useEffect, useState } from "react";
import { StyleSheet } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import Homescreen from "./screens/Homescreen";
import NewSubject from "./screens/NewSubject";
import ShowSubject from "./screens/ShowSubject";
import AsyncStorage from "@react-native-async-storage/async-storage";
const Stack = createNativeStackNavigator();
export default function App() {
let [dict, setDict] = useState({});
useEffect(() => {
loadDictionary().then(res => {
setDict(res);
});
}, []);
useEffect(() => {
safeDictionary();
}, [dict]);
async function loadDictionary() {
const value = await AsyncStorage.getItem('dict');
try {
if (value) {
return JSON.parse(value);
}
return ({});
} catch (error) {
console.log("GET ERROR AT LOAD DICTIONARY: ", error)
}
}
async function safeDictionary() {
try {
await AsyncStorage.setItem("dict", JSON.stringify(dict));
} catch (error) {
console.log("GET ERROR AT SAFE DICTIONARY:", error);
}
}
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Homescreen}
options={{ title: "Grades Calculator" }}
initialParams={{ dict, setDict }}
/>
<Stack.Screen name="New Subject" component={NewSubject} initialParams={{ dict, setDict }} />
<Stack.Screen name="Subject" component={ShowSubject} initialParams={{ dict, setDict }}/>
</Stack.Navigator>
</NavigationContainer>
);
}
希望这能帮助您
英文:
I'm programming a react native app, which calculates the average of the grades. There you can create subjects and for each subject you can add grades. For that I have difference screens. I safe it in a dictonary, which I load it into the async storage. For example:
{subject 1: [grades], subject 2: [grades] }. In real life: {math: [1, 4,2], english:[5,2]}.
But now I have the problem, when I add a subject, it loads the subject before and when I add then a new subject, only then it loading it.
Here is a video with the problem and the full code(it's the same video):
https://www.dropbox.com/s/4yqzl22zannb9ln/reactnativeproblem.mp4?dl=0
https://drive.google.com/file/d/1Wi37lmMCgYOAFQSOMOQebCWkQSsFiPaz/view?usp=sharing
Here is the code for app.js:
import { React, useEffect, useState } from "react";
import { StyleSheet } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import Homescreen from "./screens/Homescreen";
import NewSubject from "./screens/NewSubject";
import ShowSubject from "./screens/ShowSubject";
import AsyncStorage from "@react-native-async-storage/async-storage";
const Stack = createNativeStackNavigator();
export default function App() {
let [dict, setDict] = useState({});
useEffect(() => {
loadDictionary().then(res => {
setDict(res);
});
}, []);
useEffect(() => {
safeDictionary();
}, [dict]);
async function loadDictionary() {
const value = await AsyncStorage.getItem('dict');
try {
if (value) {
return JSON.parse(value);
}
return ({});
} catch (error) {
console.log("GET ERROR AT LOAD DICTONARY: ", error)
}
}
async function safeDictionary() {
try {
await AsyncStorage.setItem("dict", JSON.stringify(dict));
} catch (error) {
console.log("GET ERROR AT SAFE DICTONARY:", error);
}
}
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Homescreen}
options={{ title: "Grades Calculator" }}
initialParams={{ dict, setDict }}
/>
<Stack.Screen name="New Subject" component={NewSubject} initialParams={{ dict, setDict }} />
<Stack.Screen name="Subject" component={ShowSubject} initialParams={{ dict, setDict }}/>
</Stack.Navigator>
</NavigationContainer>
);
}
I hope anybody can help me
答案1
得分: 0
传递动态的 dict
值作为 initialParams
不建议。添加和显示主题应由它们各自的屏幕处理。
英文:
Passing dynamic dict
value as initialParams
is not recommended. Adding and displaying subjects should be handled by their respective screens.
import { React, useEffect, useState } from "react";
import { StyleSheet, View, Button, TextInput, Text } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import AsyncStorage from "@react-native-async-storage/async-storage";
const Stack = createNativeStackNavigator();
function HomeScreen(props) {
return (
<View>
<Button
title="Add Subject"
onPress={() => props.navigation.navigate("NewSubject")}
/>
</View>
);
}
function NewSubject(props) {
const [subject, setSubject] = useState("");
async function loadDictionary() {
const value = await AsyncStorage.getItem("dict");
try {
if (value) {
return JSON.parse(value);
}
return [];
} catch (error) {
console.log("GET ERROR AT LOAD DICTONARY: ", error);
}
}
async function saveDictionary() {
if (!subject) return;
try {
const prev = await loadDictionary();
const next = [...prev, subject];
await AsyncStorage.setItem("dict", JSON.stringify(next));
props.navigation.navigate("Subject");
} catch (error) {
console.log("GET ERROR AT SAFE DICTONARY:", error);
}
}
return (
<View style={{ padding: 20 }}>
<View>
<TextInput
placeholder="Type subject..."
style={{ padding: 5, borderWidth: 1 }}
onChangeText={setSubject}
/>
</View>
<View style={{ paddingVertical: 10 }}>
<Button title="Add Subject" onPress={saveDictionary} />
<Button
title="Cancel"
onPress={() => props.navigation.goBack()}
color="black"
/>
</View>
</View>
);
}
function ShowSubject(props) {
let [dict, setDict] = useState([]);
async function loadDictionary() {
const value = await AsyncStorage.getItem("dict");
try {
if (value) {
return JSON.parse(value);
}
return {};
} catch (error) {
console.log("GET ERROR AT LOAD DICTONARY: ", error);
}
}
useEffect(() => {
loadDictionary().then((res) => {
setDict(res);
});
}, []);
return (
<View>
{dict.map((subject) => (
<Text key={subject}> {subject} </Text>
))}
<View>
<Button
title="Add Subject"
onPress={() => props.navigation.navigate("NewSubject")}
/>
</View>
</View>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: "Grades Calculator" }}
/>
<Stack.Screen
name="NewSubject"
options={{ title: "New Subject" }}
component={NewSubject}
/>
<Stack.Screen name="Subject" component={ShowSubject} />
</Stack.Navigator>
</NavigationContainer>
);
}
Live Demo - https://snack.expo.dev/@emmbyiringiro/d25e82
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论