简体   繁体   English

UseEffect 中的异步 function

[英]Async function in UseEffect

I am trying to get data from AsyncStorage and eventually map this data to a list of buttons on my home screen.我正在尝试从 AsyncStorage 获取数据,并最终从 map 将此数据添加到我的主屏幕上的按钮列表中。 The data is saved to AsyncStorage from an API call that is made upon login.数据从登录时进行的 API 调用保存到 AsyncStorage。

In my async function, I am able to successfully retreive the data from AsyncStorage and parse it into JSON format, and then log it to the console.在我的异步 function 中,我能够成功地从 AsyncStorage 检索数据并将其解析为 JSON 格式,然后将其记录到控制台。 It looks like this:它看起来像这样:

{
    1 : {title:"Timesheet",component_name:"Timesheet"}
    2 : {title:"Personal Info",component_name:"PersonalInfo"}
    3 : {title:"Employee Directory",component_name:"EmployeeListing"}
}

The problem I am running into is that I can't save this data to my useState variable and then render it into the component after useState is updated by my async function.我遇到的问题是我无法将此数据保存到我的 useState 变量中,然后在我的异步 function 更新 useState 后将其渲染到组件中。 Every time I try to access this data, I either get null or a Promise object.每次我尝试访问这些数据时,我都会得到nullPromise object。 How can I access the data after useState is updated? useState 更新如何访问数据? Do I need to use a different React hook to call the Async function?我是否需要使用不同的 React 挂钩来调用 Async function?

Here is the code that I am using:这是我正在使用的代码:

import { Text, View, StyleSheet } from 'react-native';
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';


export default function HomeScreen() {

const [buttonData, setButtonData] = useState(null);

useEffect (() => {
  const loadHomeScreenButtons = async () => {
    try {
      const buttons = await AsyncStorage.getItem('app_screens').then(screens => {
        // Parse the JSON data from its stored string format into an object.
        let app_screens_json = JSON.parse(screens);
        let app_screens_list = app_screens_json.app_screens;
        console.log(app_screens_list);  // This outputs the data to the console.
        setButtonData(app_screens_list);  // Trying to set the button data in useState.
        return app_screens_list;
      });
    }
    catch (e) {
      console.log(e)
    }
  }

  loadHomeScreenButtons();

}, [])

return (
  <View style={home_styles.container}>
    <Text>{buttonData[1]["title"]}</Text>
  </View>
);

}

You just need to render a loading component until your data is fetched.你只需要渲染一个加载组件,直到你的数据被获取。

{ buttonData?.length? 
   <Text>{buttonData[1]["title"]}</Text> : <Text>...loading</Text>
}

You are getting an error as you are trying to access a property that does not exist at the render.当您尝试访问渲染中不存在的属性时,您会收到错误消息。

Try this way试试这个方法

 const loadHomeScreenButtons = useCallback(async () => { try { const screens = await AsyncStorage.getItem('app_screens') const app_screens_json = JSON.parse(screens) setButtonData(app_screens_json.app_screens) } catch (e) { console.log(e) } }, []); useEffect(() => { loadHomeScreenButtons(); }, [loadHomeScreenButtons]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM