const 变量在没有 window 重新加载的情况下不会更新

const Variables not updating without window reload

我正在尝试将我的登录页面重定向到我的主页。 我使用:

this.props.history.push("/userdashboard");

这有效,但在主页上有从 Constants.js 中提取的 const 变量,其中包含 USER_ID,从本地存储设置:

let user_id = null;
try {
  user_id =
    window.localStorage.getItem("user_info") &&
    JSON.parse(window.localStorage.getItem("user_info")).user_id;
} catch (err) {
  console.error("Error Parsing user_info user_id");
}
const USER_ID = user_id;

export { USER_ID };

然后用

导入
import { USER_ID} from "../constants/Constants";

问题在于,这些常量仍然为 null,并且在页面重新加载之前不包含新信息。

我希望能够在不使用 location.reload 的情况下执行此操作,因为有时我希望用户被推送到特定页面。

这是来自我的登录页面,该页面等待操作完成然后推送

this.props.loginFunc(login_data).then(() => this.completeLogin());

completeLogin() {
  this.props.history.push("/userdashboard");
}

我想不出刷新此 const 数据的方法。此外,我不完全确定为什么每次都使用这些常量从本地存储中获取项目,这不是预期的,并且用在足够多的地方以至于重构很痛苦。

常量的全部意义在于它们不能被重新分配。所以每次导入 Constants.js 时,它总是使用以前的 const 值。

您已经有了一个 let user_id 变量,只需将其导出即可

let user_id = null
try {
  user_id = window.localStorage.getItem("user_info") && JSON.parse(window.localStorage.getItem("user_info")).user_id
}
catch(err) {
  console.error("Error Parsing user_info user_id")
}

export {
  USER_ID: user_id,
}

我不确定 constlet(我猜与 var 相比)是否有所不同。 localStorage 被读取一次很重要。 初读后什么时候更新?我没有看到那段代码。

放这条线

user_id = window.localStorage.getItem("user_info") && JSON.parse(window.localStorage.getItem("user_info")).user_id;

如果您希望在运行时更新,脚本应检查更新的位置。