如何使用 React Native 和 AWS 确保我的个人资料信息每次都被导入?

How do I make sure my Profile information is imported every time, using React Native and AWS?

我有一个 RN/Expo 应用程序。用户可以登录并按下抽屉(汉堡包)按钮,然后查看他们的个人资料信息。此信息是从 AWS 服务器中提取的,但是否显示信息 renders/is 确实是命中注定。我希望它一直显示,但这似乎永远无法保证。

下面是我的代码:

export function DrawerContent (props){

const [ firstName, getFirstName ] = useState('')

useEffect(() =>{
    (async()=>{
    
        const displayName = async () =>{
            const real_response = await client_instance.get_user_info() //server function that calls user's info from the AWS server
                getFirstName(
                    <Text style = {styles.title}> 
                    {real_response.first_name} {real_response.last_name}
                    </Text>
                ) 
            }
displayName()

}
        )
       },
      [],
    )

... //在抽屉上的return语句中,应该在打开时呈现的地方

<View style = {{marginLeft: width*0.021, flexDirection: 'column'}}>
    <Title style = {styles.title}>{firstName}</Title>   
</View>

编辑

    //This is the final form 
const displayName = async () =>{
        const real_response = client_instance.get_user_info().then(response=>{
            
            getFirstName(
                <Text style = {styles.title}> 
                {response.first_name} {response.last_name}
                </Text>
            )
        }
        )
            console.log('response is here', real_response)
    }

照片编辑:

    const [ imageData, getImageData ] = useState(null)
        
        const displayPhoto = async () => {          
        const real_response = client_instance.download_profile_photo().then(response=>{

getImageData(
        response.raw_data
    )  
    console.log('photo is here=>',response )            
      }         
     )     
    }
        
        displayPhoto()
        
    <View>
        {imageData && <Avatar.Image source={{uri:`data:image/jpg;base64,${imageData}`}}/>}
    </View>

您可以使用 then 解析返回的 promise,并在内部调用 getFirstName 方法。

 client_instance.get_user_info().then(response => { // call getFirstName here });

我想知道您的函数是否被多次调用并可能覆盖您的函数先前获得的值。即使不是这种情况,如果 real_response 不是未定义的,最好只绑定这些服务器获取的信息。您还可以删除未使用的依赖项数组。

export function DrawerContent(props) {
  const [firstName, getFirstName] = useState("");

  useEffect(() => {
    async () => {
      const displayName = async () => {
        try {
          const real_response = await client_instance.get_user_info(); //server function that calls user's info from the AWS server
          if (real_response) {
            getFirstName("");
          } else {
            console.log("Could not fetch info from server.");
          }
        } catch (err) {
          console.log(`Error occurred fetching from server: ${err.message}`);
        }
      };
      displayName();
    };
  });
}

虽然其中一些答案有所帮助,但真正解决此问题的是在用户最初登录后缓存值并存储它们以备将来使用。此外,如果初始响应 returns 为空,服务器将继续尝试获取数据,并且在收到数据之前不会缓存。

这是一个例子:

用户注册 => 用户登录 => 填充个人资料 => 数据缓存

用户注册 => 用户登录 => 个人资料信息未填充 => 服务器再次检查直到检索到数据 => 缓存数据