2017-09-18 52 views
0

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

错误:

  • 有一个[对象对象]当我尝试设置的项目
  • 得到了一个对象,而不是一个数组
  • 试图将分配给只读属性
  • 预计一个字符串,得到一个数组

这里是代码: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}></TextInput> 
 
     </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的

提前

谢谢!

+0

'addNote()'是错误的。你应该认为这个状态是不可改变的。制作一份副本并修改副本,然后使用副本'setState'只复制一次。 –

+0

我该怎么做?请你能提供一些指导或代码吗?即时通讯仍然是这个 –

+1

谷歌的菜鸟?这里是[一](https://github.com/facebook/immutable-js/wiki/Immutable-as-React-state) –

回答

1

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

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

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

从阵营本地文档:

融合了输入值的现有键值,假设两个值被串化JSON。返回一个Promise对象。

+0

我可以建议的唯一的改进是包括一些OP的(原始海报)代码展示它如何适合他们的榜样,因为他/她提到他们是初学者。 – ContinuousLoad