首页 > 解决方案 > 在本机反应中渲染之前数据不可用

问题描述

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

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 渲染为渲染上的文本)

标签: react-native

解决方案


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

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

  • componentWillMount > 渲染 > componentDidMount。

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

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

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

该名称将继续有效,直到版本 17。


推荐阅读