在哪里调用AsyncStorage.getItem()函数来加载react-native中保存的数据?

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

我已将一个数据保存在我的react-native项目的一个类中。通过保存数据,我开始一个新的屏幕。在那个屏幕中,我正在检索保存的数据。为此,我在render函数中调用了AsyncStorage.getItem('token')函数。

这是该类的代码 -

import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';

 class NoteMeHome extends React.Component {
  state = {
    text:'',
    storedValue:'',
    getValue: ''
  };

  static navigationOptions = ({navigation}) => ({
    title: "Home",
    headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
    onPress={()=>navigation.navigate('DrawerOpen')}/>,

    drawerIcon: 

    <Image source={require('../assets/icon.png')}
            style={styles.icon}
    />
  })

  render() {
    const {storedValue} = this.state;

    AsyncStorage.getItem('token').then(value =>
      //AsyncStorage returns a promise so adding a callback to get the value
      this.setState({ getValue: value })
      //Setting the value in Text 
    );

    return(
      <Container>
        <CustomHeader
          title="Home"
          drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
        />
        <Content contentContainerStyle={{flex:1, alignItems:'center', 
        justifyContent:'center', padding:10}}>
        <Button full onPress={()=> this.props.navigation.navigate('Settings')}>
          <Text style={{color:'white'}}>{storedValue}</Text>
        </Button>
        <Text>{this.state.getValue}</Text>
        </Content>
      </Container>
    )
  }

}

const styles = StyleSheet.create({
  icon:{
    height: 24,
    width: 24
  }
})
export default NoteMeHome;

之后,在运行项目时,在上面提到的类中,当我单击任何抽屉项目转到另一个屏幕时,它在控制台中显示以下错误 -

wanrning:无法在未安装的组件上调用setState(或forceUpdate)。这是no-op,但它表示应用程序中存在内存泄漏。要修复,请取消componentWillUnmount方法中的所有订阅和异步任务。

我猜AsyncStorage.getItem('token')函数调用出了问题,因为如果删除该函数它不会显示任何警告。

所以,如果有人帮助我知道我应该在哪里拨打以下代码,那将是非常好的 -

AsyncStorage.getItem('token').then(value =>
  //AsyncStorage returns a promise so adding a callback to get the value
  this.setState({ getValue: value })
  //Setting the value in Text 
);

删除警告?

javascript react-native
3个回答
1
投票

阿西夫,

这就是我的想法:

import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';

 class NoteMeHome extends React.PureComponent {
  state = {
    text:'',
    storedValue:'',
    getValue: ''
  };

  static navigationOptions = ({navigation}) => ({
    title: "Home",
    headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
    onPress={()=>navigation.navigate('DrawerOpen')}/>,

    drawerIcon: 

    <Image source={require('../assets/icon.png')}
            style={styles.icon}
    />
  });
  
  componentDidMount() {
    const token = await AsyncStorage.getItem('token');
    this.setState({ getValue: token });
  }

  render() {
    const {storedValue, getValue} = this.state;
    return(
      <Container>
        <CustomHeader
          title="Home"
          drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
        />
        <Content contentContainerStyle={{flex:1, alignItems:'center', 
        justifyContent:'center', padding:10}}>
        <Button full onPress={()=> this.props.navigation.navigate('Settings')}>
          <Text style={{color:'white'}}>{storedValue}</Text>
        </Button>
        <Text>{getValue}</Text>
        </Content>
      </Container>
    )
  }

}

const styles = StyleSheet.create({
  icon:{
    height: 24,
    width: 24
  }
})
export default NoteMeHome;

我不知道在你的情况下你是否应该尝试处理组件的更新,因为你没有任何道具。

问候,


0
投票

IMO你应该使用componentDidMount来做你想在屏幕开头做的任何事情。要使用AsyncStorage,请记住这是一个asynchronous函数,因此您必须等待函数完成才能获得该值。 有关react native组件的更多信息,请参阅this 有关使用async“等待”AsyncStorage的更多信息,请参阅this示例


0
投票

在反应组分中,render()应始终保持纯净。一个人永远不应该在渲染函数中设置状态,这是一个非常糟糕的实践,在一个简单的组件中它可能正常工作。它只能因为异步性而起作用。

您应该使用componentDidMount生命周期方法从本地存储中获取数据。

componentDidMount() {
    const token = await AsyncStorage.getItem('token');
    this.setState({ getValue: token });
}
© www.soinside.com 2019 - 2024. All rights reserved.