JavaScript localStorage 无法跨多个文件更新

问题描述 投票:0回答:1

我想在 localStorage 中存储一个整数,并能够在多个 JavaScript 文件上使用它。但是,即使我将其设置为新值,其他文件仍然引用旧值。

这是我正在使用的 JSON 文件的压缩版本:

export const data = [
    {
        "username": "steve"
    },
    {
        "username": "fred"
    }

这是我设置 localStorage 键值的代码:

import { renderMenu } from "./menuPage.js";
import { data } from "../data/data.js"; // JSON file containing data

const usernameInput = document.createElement("input");
const btn = document.createElement("btn");

btn.addEventListener("click", (ev) => {
    var username = usernameInput.value;

    const user = data.find(u => (u.username === username));

    if (!user) {
        errText.textContent = "Incorrect username";
    } else {
        var dataIndex = data.indexOf(user);
        console.log(dataIndex);
    
        if (localStorage.getItem("dataIndexLocalStorage") !== dataIndex) {
            localStorage.setItem("dataIndexLocalStorage", JSON.stringify(dataIndex));
        }
        renderMenu();
    }
}

例如,如果我输入的用户名是“steve”,我希望

console.log(dataIndex);
输出
0

这是我获取 localStorage 键值的代码(此代码用于多个 JavaScript 文件):

import { data } from "../data/data.js";
const dataIndex = parseInt(localStorage.getItem("dataIndexLocalStorage"));

export function renderMenu() {
    console.log(dataIndex);
}

按照前面所说的例子,我仍然期望

console.log(dataIndex);
输出
0
。在某些情况下它会这样做(有时它只是输出
null
)。

在确实输出

0
的情况下,如果我输入“fred”作为用户名,我希望
console.log(dataIndex);
输出
1
。但是,在 renderMenu() 函数中,
console.log(dataIndex);
仍然输出
0
,而不是像主代码中那样输出
1

我错过了一些非常基本的东西吗?奇怪的是它没有到处更新值。

我很感激我能得到的任何帮助:)

javascript local-storage
1个回答
0
投票

我现在回答这个问题以防其他人遇到这个问题:

我只需将 dataIndex = parseInt(...) 放入 renderMenu 函数中,并在文件顶部将 var dataIndex 声明为全局变量:

import { data } from "../data/data.js";
var dataIndex;

export function renderMenu() {
    dataIndex = parseInt(localStorage.getItem("dataIndexLocalStorage"));
    console.log(dataIndex);
}
© www.soinside.com 2019 - 2024. All rights reserved.