【问题标题】:Why is AsyncStorage not retrieving data once I refresh my App?为什么刷新我的应用程序后 AsyncStorage 不检索数据?
【发布时间】:2021-05-13 08:54:27
【问题描述】:

我正在构建一个待办事项应用程序,我正在尝试存储和检索数据,但它没有检索任何正在存储的数据。一旦我刷新数据似乎不会持续存在。如果有另一种存储或编写我的代码的方式,请提供帮助。我尝试使用其他存储方法,例如 MMKV,但它与 AsyncStorage 类似,所以我决定坚持使用 AsyncStorage。这是我的代码:

import AsyncStorage from "@react-native-async-storage/async-storage";

export default function todaytodo() {
  const [modalOpen, setModalOpen] = useState(false);

  const [todos, setTodos] = useState("");

  const storedata = async () => {
    try {
      await AsyncStorage.setItem("Todos", JSON.stringify(todos));
    } catch (err) {
      console.log(err);
    }
  };

  const loadData = async () => {
    try {
      const value = await AsyncStorage.getItem("Todos");
      if (value !== null) {
        console.log(value);
        return value;
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    storedata();
    loadData();
  });

  const toggleComplete = (index) =>
    setTodos(
      todos.map((Todo, k) =>
        k === index ? { ...Todo, complete: !Todo.complete } : Todo
      )
    );

  const pressHandler = (key) => {
    setTodos((prevTodos) => {
      return prevTodos.filter((todo) => todo.key != key);
    });
  };

  const submitHandler = (Todo) => {
    Todo.key = Math.random().toString();
    setTodos((currentTodo) => {
      return [Todo, ...currentTodo];
    });
    setModalOpen(false);
  };

  return (
    <View style={styles.container}>
      <View>
        <View>
          <Ionicons
            style={{
              position: "absolute",
              marginTop: 650,
              alignSelf: "flex-end",
              zIndex: 10,
              marginRight: 5,
            }}
            name="md-add-circle-outline"
            size={73}
            color="black"
            onPress={() => setModalOpen(true)}
          />
        </View>

        <FlatList
          data={todos}
          renderItem={({ item, index, complete }) => (
            <TouchableOpacity onPress={() => toggleComplete(index)}>
              <ScrollView>
                <View style={styles.everything}>
                  <View style={styles.itemlist}>
                    <Checkbox
                      label="delete"
                      checked={true}
                      onPress={() => pressHandler(item.key)}
                    />
                    <Text
                      style={{
                        marginLeft: 8,
                        marginTop: 5,
                        fontSize: 15,
                        textDecorationLine: item.complete
                          ? "line-through"
                          : "none",
                        color: item.complete ? "#a9a9a9" : "black",
                      }}
                    >
                      {item.Todo}
                    </Text>
                  </View>
                  <Text
                    style={{
                      fontSize: 12,
                      marginLeft: 50,
                      marginTop: -15,
                      color: "#008b8b",
                      textDecorationLine: item.complete
                        ? "line-through"
                        : "none",
                      color: item.complete ? "#a9a9a9" : "#008b8b",
                    }}
                  >
                    {item.Comment}
                  </Text>
                </View>
              </ScrollView>
            </TouchableOpacity>
          )}
        />
      </View>
      <View style={styles.modalcont}>
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
          <RNModal visible={modalOpen} animationType="slide">
            <View style={styles.modalContent}>
              <Ionicons
                name="md-close-circle-outline"
                style={{ alignSelf: "center" }}
                size={60}
                color="black"
                onPress={() => setModalOpen(false)}
              />
              <AddForm submitHandler={submitHandler} />
            </View>
          </RNModal>
        </TouchableWithoutFeedback>
      </View>
    </View>
  );
}

【问题讨论】:

    标签: react-native asyncstorage


    【解决方案1】:

    useEffect 的使用在这里是可疑的,如果你想在加载组件时执行一次 然后需要更新useEffect的代码。

    useEffect(() => {
      storedata();
      loadData();
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多