【问题标题】:JavaScript Object is not assigned properlyJavaScript 对象未正确分配
【发布时间】:2020-09-23 10:51:21
【问题描述】:

我无法理解为什么会发生这种情况

我正在使用 React 创建一个网络应用

我有一个名为 user_info 的 Javascript 对象

var user_info = {
    username: '',
    password: '',
    f_name: ''
};

现在我想将这些值分配给我从我的 firebase 实时数据库中获取的值。

 db.ref("/users").on("value", snapshot => {                           
            
            alert("Firebase " + snapshot.child("username").val()) // Got the value correctly.....

            user_info.username = snapshot.child("username").val();
            user_info.password = snapshot.child("password").val(); //Assigning it to the object...
            user_info.f_name = snapshot.child("f-name").val();
            
            alert("Firebase Username = " + user_info.username); //Assigned Successfully...
           
        });

在这段代码之后(snapshot function 之外),我使用alert() 再次显示用户名。

alert(user_info.username); // No value is displayed here.

我猜快照中的值没有分配给对象user_info。稍后我将导出此对象并将其导入另一个文件中,我遇到了同样的问题。

export {user_info};

--- 在其他文件中 ---------

import React from 'react';
import {user_info} from './users.js';

function LandingPage()
{
  return(
      <div className="container">
         <h1>Welcome {user_info.username}</h1> // Only 'Welcome' is displayed
      </div>
   );
}

export default LandingPage;

我不明白为什么没有将值分配给对象user_info。请更正我的代码,以便我可以将值存储在我的对象中。

谢谢。

【问题讨论】:

    标签: javascript reactjs firebase-realtime-database javascript-objects


    【解决方案1】:

    值已更新,但组件未在此处重新渲染使用状态(useState 挂钩),然后从状态渲染它。 并在“user_info”更新时使用 useEffect 挂钩来更新状态。

    import React,{useState,useEffect} from 'react';
    import {user_info} from './users.js';
    
    function LandingPage()
    {
    const [userInfo,setUserInfo]=useState({});
    
    useEffect(()=>{
    setUserInfo(user_info);
    },[user_info]);
    
    
      return(
          <div className="container">
             <h1>Welcome {userInfo?.username}</h1> // Only 'Welcome' is displayed
          </div>
       );
    }
    
    export default LandingPage;
    

    https://reactjs.org/docs/state-and-lifecycle.html

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 2014-04-24
      • 1970-01-01
      • 2019-02-24
      • 2020-11-05
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多