这是用localstorage
存储项目和任务的正确方法吗?每次刷新页面时,我还需要获取localstorage
。那么我该怎么做呢?
export function newProject(name) {
allProjects.push({
projectTitle: name,
id: crypto.randomUUID(),
tasks: []
})
getProjectId(name)
save(name, project)
}
export function save(title, task) {
localStorage.setItem(title, JSON.stringify(task))
}
项目未定义,因此需要先定义它。
const project = {
projectTitle: name,
id: crypto.randomUUID(),
tasks: []
}
allProjects.push(project)
getProjectId(name)
save(name, project)
要刷新所有项目,您需要在localstorage中维护一个名称数组,或者将所有项目保存为一键数组。
编辑:所以这个问题并没有完全描述清楚,但我已经尽力了。将导出添加到所需的函数中,并在需要时使用getProjectId。我使用了一种带有独立ID数组的方法来维护项目列表。
function createNewProject(name) {
// create and return project object
return {
title: name,
id: crypto.randomUUID(),
tasks: []
};
}
function saveProject(storageKey, projectObject) {
// get current list of project keys or create new list
const allProjectKeys = JSON.parse(localStorage.getItem("allProjectKeys")) ?? [];
// add new one to the list
allProjectKeys.push(storageKey);
// save current list of project keys
localStorage.setItem("allProjectKeys", JSON.stringify(allProjectKeys));
// save project data
localStorage.setItem(storageKey, JSON.stringify(projectObject));
}
function getProjectByKey(storageKey) {
// get single project by given key
return JSON.parse(localStorage.getItem(storageKey));
}
function getAllProjects() {
// get list of all project keys, and map each of them to get actual project instead of project key
return JSON.parse(localStorage.getItem("allProjectKeys")).map(getProjectByKey);
}
const testProject = createNewProject("test");
saveProject(testProject.id, testProject);
console.log(getProjectByKey(testProject.id));
console.log(getAllProjects());