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 渲染为渲染上的文本)
解决方案
就像每个人都分享的那样,您可能希望在 componentWillMount 之后调用您的函数(在 componentDidMount 期间调用)。不确定为什么需要渲染数据,但我认为您需要根据永久存储来渲染 UI。
根据您的编辑,“我尝试在 ComponentDidMount() 上运行,但在渲染过程开始之前数据不可用”。该说法不正确,因为生命周期如下:
- componentWillMount > 渲染 > componentDidMount。
这意味着,UI 已经呈现。然后您的函数将在 componentDidMount 处触发。
如果您在 componentDidMount 中没有看到您的数据,请调试以验证数据是否确实存在于您的永久存储中?
旁注:您应该考虑停止使用ComponentWillMount。
该名称将继续有效,直到版本 17。
推荐阅读
- c# - 当使用无参数 View() 重新调用视图时,视图正在缓存其先前的数据 - 当我不希望它时
- google-dfp - Google Ad Manager - 同一订单项在屏幕上投放所有广告单元,即使它没有足够的广告素材
- android - 用于屏幕指纹的 Android API
- internationalization - i18next-browser-languageDetector 路径不起作用
- python - 使用 Pandas 动态创建数据框
- python - Cython 中的“仅限 C”类
- maven - 使用配置文件创建分解的 JAR 文件
- git - 通过命令行从 Azure Devops 下载应用程序
- javascript - 从 Blazor 使用 JSInterop 读取输入文件
- python-3.x - Python 代码中的错误:应用 style_function 方法更改颜色后,编译器给我一个错误