在渲染本机之前数据不可用

时间:2019-10-14 13:04:19

标签: react-native

我正在尝试从我的应用程序开头的永久存储中提取数据,然后使用该数据运行登录功能,但是当我尝试运行该功能时,该数据不可用。 示例:

import store from 'react-native-simple-store'

class ExampleScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      username: "",
      password: ""
    }

  componentWillMount(){
    try {
      store.get('User').then((User) => this.setState({username: User}));
      store.get('Pass').then((Pass) => this.setState({password: Pass}));
    } catch(error){
      alert(error)
    };
    this.onSubmitPress;
  }

  onSubmitPress = async () => {
    alert(this.state.username);
    alert(this.state.password);
  }
}

该函数返回在开头(“”)上设置的空状态。

如何使用渲染前获得的数据运行函数?

Edit1:在渲染登录屏幕之前,我需要渲染之前的数据才能运行登录功能。 我尝试在ComponentDidMount()上运行,但是在渲染过程开始之前数据不可用(我可以在渲染器上将this.state.username渲染为文本)

2 个答案:

答案 0 :(得分:0)

您不能保证可以在渲染之前获取数据。您只能在上一个屏幕中获取数据,或在当前屏幕中显示一个ActivityIndi​​cator来等待。

答案 1 :(得分:0)

就像每个人都共享的一样,您可能想在componentWillMount之后调用您的函数(在componentDidMount期间调用)。不确定为什么需要渲染数据,但是我认为您需要根据永久存储来渲染UI。

根据您的编辑,“ 我尝试在ComponentDidMount()上运行,但是直到渲染过程开始之前,数据才可用”。该语句不正确,因为生命周期如下:

  • componentWillMount>渲染> componentDidMount。

这意味着UI已呈现。然后您的函数将在componentDidMount处触发。

如果您在componentDidMount中看不到数据,请进行调试以验证数据是否确实存在于您的永久存储中?

旁注:您应该考虑停止使用ComponentWillMount

  

该名称将一直使用到版本17。