AsyncStorage React Native保存数组

问题描述 投票:0回答:1

我尝试保存一个数组,我试图按照文档但但失败了。我应该如何编写它以便它不会给我各种警告和错误。

错误:

  • 我尝试设置项目时得到一个[对象]
  • 有一个对象而不是一个数组
  • 尝试分配给只读属性
  • 期待一个字符串,得到一个数组

这是代码:App.js

 import React from "react";
 import {
  StyleSheet,
  Text,
  View,
  TextInput,
  ScrollView,
  TouchableOpacity,
  KeyboardAvoidingView,
  AsyncStorage
} from "react-native";
import Note from "./app/components/note";

export default class App extends React.Component {
 state = {
    noteArray: [],
    noteText: ""
};

render() {
    let notes = this.state.noteArray.map((val, key) => {
        return (
            <Note
                key={key}
                keyval={key}
                val={val}
                deleteMethod={() => this.deleteNote(key)}
            />
        );
    });

    return (
        <KeyboardAvoidingView behavior="padding" style={styles.container}>
            <View style={styles.header}>
                <Text style={styles.headerText}>Tasker</Text>
            </View>

            <ScrollView style={styles.scrollContainer}>{notes}</ScrollView>

            <View style={styles.footer}>
                <TouchableOpacity
                    onPress={this.addNote.bind(this)}
                    style={styles.addButton}
                >
                    <Text style={styles.addButtonText}>+</Text>
                </TouchableOpacity>

                <TextInput
                    style={styles.textInput}
                    placeholder="Enter Task..."
                    placeholderTextColor="white"
                    underlinedColorAndroid="transparent"
                    onChangeText={noteText => this.setState({ noteText })}
                    value={this.state.noteText}
                />
            </View>
        </KeyboardAvoidingView>
    );
}

addNote() {
    if (this.state.noteText) {
        var d = new Date();
        this.state.noteArray.push({
            date:
                d.getFullYear() +
                "/" +
                (d.getMonth() + 1) +
                "/" +
                d.getDate(),
            note: this.state.noteText
        });
        this.setState({ noteArray: this.state.noteArray });
        this.setState({ noteText: "" });
    }

    //AsyncStorage.setItem() How do I write it so no errors occur
    alert({ noteArray: this.state.noteArray });
}
}

额外注意:错误在我的手机上的Android和iOS上的Expo App上

提前致谢!

javascript arrays react-native expo asyncstorage
1个回答
1
投票

数组和其他对象需要在AsyncStorage中保存为字符串。

AsyncStorage.setItem('arrayObjKey', JSON.stringify(myArray));

此外,如果您需要更新数组中的值,请使用AsyncStorage.multiMerge

从React-Native文档:

将现有键值与输入值合并,假设两个值都是字符串化JSON。返回Promise对象。

© www.soinside.com 2019 - 2024. All rights reserved.