AsyncStorage.setItem每次都会崩溃,在Android,Expo上完美运行

时间:2018-01-12 22:11:24

标签: ios react-native expo

以下是我导入的内容:

import React, { Component } from 'react'
import {
  Image,
  Text,
  TextInput,
  Keyboard,
  KeyboardAvoidingView,
  TouchableOpacity,
  View,
  Linking,
  AsyncStorage,
  Alert
} from 'react-native'

这是设置状态的函数(从下面的TextInput调用)

setName = (name, value) => {
    AsyncStorage.setItem(name, value);
}

以下是它的调用方式

<TextInput
    keyboardType='default'
    autoCapitalize='words'
    returnKeyType='next'
    onSubmitEditing={() => this.lastNamedRef.focus()}
    underlineColorAndroid='transparent'
    style={{flex:1}}
    placeholder='Your first name'
    value={this.state.firstName}
    onChangeText={(text) => [this.validateInputLength(text, 2, 50, 'firstName'), this.setName('firstName', this.state.firstName)]}
 />

<TextInput
    keyboardType='default'
    autoCapitalize='words'
    returnKeyType='done'
    ref={lastNameRef => this.lastNamedRef = lastNameRef}
    underlineColorAndroid='transparent'
    style={{flex:1}}
    placeholder='Your last name'
    value={this.state.lastName}
    onChangeText={(text) => [this.validateInputLength(text, 2, 50, 'lastName'), this.setName('lastName', this.state.lastName)]}
 />

如果我从TextInput中的onChangeText中删除this.setName()函数,该应用程序不会崩溃,但是当它在那里时,它会在iOS上崩溃,但不会在Android上崩溃。当使用setName函数更新componentWillMount()(下面)时,this.state.firstName和this.state.lastName来自AsyncStorage

componentWillMount() {
    AsyncStorage.getItem('firstName').then((value) => this.setState({firstName:value}))
    AsyncStorage.getItem('lastName').then((value) => this.setState({lastName:value}))
}

componentWillMount()中的AsyncStorage.getItem不会使应用程序崩溃,但似乎不会将数据加载到字段中。大多数时候它会加载,但不是每次都加载。 AsyncStorage一般看起来超级越野车。

这是validateInputLength函数

validateInputLength = (text, min=10, max=25, type) => {
  if(text.length < min || text.length > max) {
    if(type=='firstName') {
      this.setState({firstName:text})
      this.setState({firstNameValidated:false})
      return false;
    } else if (type=='lastName') {
      this.setState({lastName:text})
      this.setState({lastNameValidated:false})
      return false;
    }
  } else {
    if(type=='firstName') {
      this.setState({firstName:text})
      this.setState({firstNameValidated:true})
    } else if (type=='lastName') {
      this.setState({lastName:text})
      this.setState({lastNameValidated:true})
    }
  }
}

......这里是构造函数

constructor(props) {
  super(props)
  this.state = {
    firstName: '',
    lastName: '',
    firstNameValidated: false,
    lastNameValidated: false,
  };
}

这会在iOS上崩溃,无论是在我的iPhone上还是在模拟器中运行,都没有显示任何错误。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

如果您尝试存储JSON对象以进行例如expo崩溃,则只能在AsyncStorage中存储字符串,这可能是发生的事情,在存储对象之前尝试使用JSON.stringify