【问题标题】:How to save Data on the local Storage in React如何在 React 中将数据保存在本地存储中
【发布时间】:2023-03-15 20:36:01
【问题描述】:

我是 React 新手,我想为我的 Android 智能手机构建一个应用程序。

我现在正在对此进行测试,它一直有效,直到我想保存一些数据,因为每次我关闭应用程序时,我想保留的数据都会被删除。 我搜索了解决此问题的选项,并尝试使用我认为已过时的 asyncstorage 和 localStorage 进行尝试,当我将其作为 apk 安装在手机上时,它不再起作用....

是否有其他选择,或者它必须与其中任何一个一起使用?还是我完全走错了路,它的工作方式完全不同?

我尝试了不同的方法,但不知何故我做错了。

编辑: 使用 LocalStorage.setItem() 和 .getItem() 它至少在网络浏览器中工作。所以我不认为这可能是代码?

App.js:

import React, {useState} from 'react';
import { Platform, StyleSheet, Text, View, KeyboardAvoidingView, TextInput, TouchableOpacity, Keyboard } from 'react-native';
import Task from './components/Task';

export default function App() {

  if (localStorage.getItem("storedtasks") == null) {
    var storedtasks = new Array;
  } else {
    var storedtasks = JSON.parse(localStorage.getItem("storedtasks"));
  }

  const [task, setTask] = useState();

  const handleAddTask = () => {
    Keyboard.dismiss();
    storedtasks.push(task);
    localStorage.setItem('storedtasks', JSON.stringify(storedtasks));
    setTask("");
  }

  const completeTask = (index) => {
    storedtasks.splice(index, 1);
    localStorage.setItem('storedtasks', JSON.stringify(storedtasks));
    window.location.reload();
  }

  return (
    <View style={styles.container}>
      
      {/*Today's Tasks */}
      <View style={styles.tasksWrapper}>
        <Text style={styles.sectionTitle}>Today's Tasks</Text>

        <View style={styles.items}>
          {/* This is where the tasks will go */}
          {
            storedtasks.map((item, index) => {
              return (
                <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                  <Task text={item} />
                </TouchableOpacity>
              )
            })
          }

        </View>

      </View>

      {/* Write a task */}
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.writeTaskWrapper}
      >
        <TextInput style={styles.input} placeholder={'Write a Task.'} value={task} onChangeText={text => setTask(text)}/>

        <TouchableOpacity onPress={() => handleAddTask()}>
          <View style={styles.addWrapper}>
            <Text style={styles.addText}>+</Text>
          </View>
        </TouchableOpacity>

      </KeyboardAvoidingView>


    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E8EAED',
    //alignItems: 'center',
    //justifyContent: 'center',
  },
  tasksWrapper: {
    paddingTop: 80,
    paddingHorizontal: 20,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  items: {
    marginTop: 30,
  },
  writeTaskWrapper: {
    position: 'absolute',
    bottom: 60,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  input: {
    paddingVertical: 15,
    paddingHorizontal: 15,
    backgroundColor: '#FFF',
    borderRadius: 60,
    borderColor: '#C0C0C0',
    borderWidth: 1,
    width: 250,
  },
  addWrapper: {
    width: 60,
    height: 60,
    backgroundColor: '#FFF',
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: '#C0C0C0',
    borderWidth: 1,
  },
  addText: {},
});

Task.js:

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const Task = (probs) => {
    

    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{probs.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#fff',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,
    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: 0.4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',
    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5,
    },
});

export default Task;

【问题讨论】:

  • 你在使用 react native 吗?
  • 你能分享你的代码吗?有沙盒就更好了
  • 是的,我添加了代码

标签: javascript android reactjs


【解决方案1】:

由于 AsyncStorage 已被弃用!在反应原生 使用 react-native-mmkv 比 AsyncStorage 快 30 倍!

npm install react-native-mmkv

你可以这样使用

设置:

import { MMKV } from 'react-native-mmkv';

MMKV.set('user.name', 'Marc')
MMKV.set('user.age', 20)
MMKV.set('is-mmkv-fast-asf', true)

获取:

import { MMKV } from 'react-native-mmkv';

const username = MMKV.getString('user.name') // 'Marc'
const age = MMKV.getNumber('user.age') // 20
const isMmkvFastAsf = MMKV.getBoolean('is-mmkv-fast-asf') // true

删除:

import { MMKV } from 'react-native-mmkv';
MMKV.delete('user.name')

查看更多文档here

【讨论】:

  • 谢谢。我会试试看。我怎么能找到这样的东西?你是怎么搜索的?
  • 思想React Native官网。有多种库建议用于替换 AsyncStorage。
  • 我正在使用博览会。 MMKV 和 Expo 有问题吗?我尝试了 MMKV,但出现错误“MMKV.getString 不是函数”。
  • 没问题。试试吧。它应该支持博览会。
  • 是否有完整的设置用户指南?我在这个网站上测试了它:https://github.com/mrousavy/react-native-mmkvhttps://github.com/mrousavy/react-native-mmkv/blob/master/INSTALL.md With react-native-reanimated。它不起作用。
【解决方案2】:

或者你可以使用react-native-async-storage

使用 npm:

npm install @react-native-async-storage/async-storage

用纱线:

yarn add @react-native-async-storage/async-storage

使用 Expo CLI:

expo install @react-native-async-storage/async-storage

您可以找到文档here

【讨论】:

  • 但是异步存储没有被弃用吗?
  • 不是这个@Zniets
  • 我添加了这个来保存:
    AsyncStorage.setItem('storedtasks', JSON.stringify(storedtasks));
    和这个来获取数据:var storedtasks = JSON.parse(AsyncStorage.getItem("storedtasks")); 但是如果我重新启动应用程序,数据不会保存。跨度>
猜你喜欢
  • 2021-09-21
  • 2021-12-25
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多