如何从 localStorage 中的对象数组访问值

How to access a value from an array of objects in localStorange

我正在尝试访问 Javascript 中对象数组的值,然后更新它。

我该怎么做?

我在本地存储中的对象数组:

[{"task":"study","completed":false,"createdDate":"Sat, 30 Jan 2021 18:24:44 GMT","id":"9153"},{"task":"programming","completed":false,"createdDate":"Sat, 30 Jan 2021 18:24:40 GMT","id":"0"}]

我的代码:

const Edit = ({ todo, setEdit, setEditInput, editInput }) => {

  const inputTextHandler = (e) => {
    setEditInput(e.target.value);
  }
  
  const updateTask = () => {
    let todoLocal = JSON.parse(localStorage.getItem("todos"));
    setEdit(false); // remove the input and show the task value
  }
  
  return (
    <div>
      <input type="text" value={editInput} onChange={inputTextHandler} autoFocus />
      <button onClick={updateTask}>
        <i className="fas fa-save"></i>
      </button>
    </div>    
  );

我通常会创建一些实用函数来完成它。像这样

// utils/localStorage.js
export function getItem(keyName) {
  try {
    return JSON.parse(localStorage.getItem(keyName));
  } catch (error) {
    console.log(error);
    return null;
  }
}

export function setItem(keyName, value) {
  localStorage.setItem(keyName, JSON.stringify(value));
}

export function removeItem(keyName) {
  localStorage.removeItem(keyName);
}

export function clearAll() {
  localStorage.clear();
}

将数组加载到内存中。做你的修改。将其转换为字符串并将其添加回本地存储。

// Load to memory
var todos = JSON.parse(localStorage.getItem('todos'))    
// Update todos
todos[0].completed = true
// Stringify and add it back to local storage
localStorage.setItem('todos',JSON.stringify(todos))