React Native异步存储问题。它只在加载项目之前加载。

huangapple go评论68阅读模式
英文:

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>
  );
}

希望这能帮助您 React Native异步存储问题。它只在加载项目之前加载。

英文:

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 &quot;react&quot;;
import { StyleSheet } from &quot;react-native&quot;;
import { NavigationContainer } from &quot;@react-navigation/native&quot;;
import { createNativeStackNavigator } from &quot;@react-navigation/native-stack&quot;;
import Homescreen from &quot;./screens/Homescreen&quot;;
import NewSubject from &quot;./screens/NewSubject&quot;;
import ShowSubject from &quot;./screens/ShowSubject&quot;;
import AsyncStorage from &quot;@react-native-async-storage/async-storage&quot;;
const Stack = createNativeStackNavigator();
export default function App() {
let [dict, setDict] = useState({});
useEffect(() =&gt; {
loadDictionary().then(res =&gt; {
setDict(res);
});
}, []);
useEffect(() =&gt; {
safeDictionary();
}, [dict]);
async function loadDictionary() {
const value = await AsyncStorage.getItem(&#39;dict&#39;);
try {
if (value) {
return JSON.parse(value);
}
return ({});
} catch (error) {
console.log(&quot;GET ERROR AT LOAD DICTONARY: &quot;, error)
}
}
async function safeDictionary() {
try {
await AsyncStorage.setItem(&quot;dict&quot;, JSON.stringify(dict));
} catch (error) {
console.log(&quot;GET ERROR AT SAFE DICTONARY:&quot;, error);
}
}
return (
&lt;NavigationContainer&gt;
&lt;Stack.Navigator&gt;
&lt;Stack.Screen
name=&quot;Home&quot;
component={Homescreen}
options={{ title: &quot;Grades Calculator&quot; }}
initialParams={{ dict, setDict }}
/&gt;
&lt;Stack.Screen name=&quot;New Subject&quot; component={NewSubject} initialParams={{ dict, setDict }} /&gt;
&lt;Stack.Screen name=&quot;Subject&quot; component={ShowSubject} initialParams={{ dict, setDict }}/&gt;
&lt;/Stack.Navigator&gt;
&lt;/NavigationContainer&gt;
);
}

I hope anybody can help me React Native异步存储问题。它只在加载项目之前加载。

答案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 &quot;react&quot;;
import { StyleSheet, View, Button, TextInput, Text } from &quot;react-native&quot;;
import { NavigationContainer } from &quot;@react-navigation/native&quot;;
import { createNativeStackNavigator } from &quot;@react-navigation/native-stack&quot;;
import AsyncStorage from &quot;@react-native-async-storage/async-storage&quot;;

const Stack = createNativeStackNavigator();

function HomeScreen(props) {
  return (
    &lt;View&gt;
      &lt;Button
        title=&quot;Add Subject&quot;
        onPress={() =&gt; props.navigation.navigate(&quot;NewSubject&quot;)}
      /&gt;
    &lt;/View&gt;
  );
}

function NewSubject(props) {
  const [subject, setSubject] = useState(&quot;&quot;);

  async function loadDictionary() {
    const value = await AsyncStorage.getItem(&quot;dict&quot;);
    try {
      if (value) {
        return JSON.parse(value);
      }
      return [];
    } catch (error) {
      console.log(&quot;GET ERROR AT LOAD DICTONARY: &quot;, error);
    }
  }

  async function saveDictionary() {
    if (!subject) return;
    try {
      const prev = await loadDictionary();

      const next = [...prev, subject];
      await AsyncStorage.setItem(&quot;dict&quot;, JSON.stringify(next));

      props.navigation.navigate(&quot;Subject&quot;);
    } catch (error) {
      console.log(&quot;GET ERROR AT SAFE DICTONARY:&quot;, error);
    }
  }
  return (
    &lt;View style={{ padding: 20 }}&gt;
      &lt;View&gt;
     
        &lt;TextInput
          placeholder=&quot;Type subject...&quot;
          style={{ padding: 5, borderWidth: 1 }}
          onChangeText={setSubject}
        /&gt;
      &lt;/View&gt;

      &lt;View style={{ paddingVertical: 10 }}&gt;
        &lt;Button title=&quot;Add Subject&quot; onPress={saveDictionary} /&gt;
        &lt;Button
          title=&quot;Cancel&quot;
          onPress={() =&gt; props.navigation.goBack()}
          color=&quot;black&quot;
        /&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  );
}

function ShowSubject(props) {
  let [dict, setDict] = useState([]);
  async function loadDictionary() {
    const value = await AsyncStorage.getItem(&quot;dict&quot;);
    try {
      if (value) {
        return JSON.parse(value);
      }
      return {};
    } catch (error) {
      console.log(&quot;GET ERROR AT LOAD DICTONARY: &quot;, error);
    }
  }

  useEffect(() =&gt; {
    loadDictionary().then((res) =&gt; {
      setDict(res);
    });
  }, []);

  return (
    &lt;View&gt;
      {dict.map((subject) =&gt; (
        &lt;Text key={subject}&gt; {subject} &lt;/Text&gt;
      ))}
      &lt;View&gt;
        &lt;Button
          title=&quot;Add Subject&quot;
          onPress={() =&gt; props.navigation.navigate(&quot;NewSubject&quot;)}
        /&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  );
}
export default function App() {
  return (
    &lt;NavigationContainer&gt;
      &lt;Stack.Navigator&gt;
        &lt;Stack.Screen
          name=&quot;Home&quot;
          component={HomeScreen}
          options={{ title: &quot;Grades Calculator&quot; }}
        /&gt;
        &lt;Stack.Screen
          name=&quot;NewSubject&quot;
          options={{ title: &quot;New Subject&quot; }}
          component={NewSubject}
        /&gt;
        &lt;Stack.Screen name=&quot;Subject&quot; component={ShowSubject} /&gt;
      &lt;/Stack.Navigator&gt;
    &lt;/NavigationContainer&gt;
  );
}


Live Demo - https://snack.expo.dev/@emmbyiringiro/d25e82

huangapple
  • 本文由 发表于 2023年1月8日 22:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定