首页 > 解决方案 > 使用 react-hooks 在文本区域中显示本地存储值

问题描述

我正在尝试在 React 中做一个笔记应用程序。

我设法将状态保存在本地存储中。

我的目标是textarea在渲染和刷新中显示本地存储“注释”。到目前为止,在刷新时,占位符显示在渲染上。

我想要:

继承人的代码:

const [notes, setNotes] = useState("")

useEffect(() => {
  const notes = localStorage.getItem("notes")
  if (notes) {
    setNotes(JSON.parse(notes))
  }
})

const handleChange = e => {
  setNotes(e.target.value)
  localStorage.setItem("notes", JSON.stringify(e.target.value))
}

return (
  <form>
    <label for="pad">
      <span>Add your notes</span>
      <textarea
        rows="10"
        placeholder="Add notes here "
        name="pad"
        onChange={handleChange}
      ></textarea>
    </label>
  </form>
)

标签: javascriptreactjsreact-hooks

解决方案


value使用带有notes变量的文本区域。对于此示例,您不需要 useEffect。即使你想使用它,也请添加你的依赖数组。

export default function App() {
  const localNotes = localStorage.getItem("notes");
  const [notes, setNotes] = useState(localNotes);

  const handleChange = e => {
    localStorage.setItem("notes", e.target.value);
    setNotes(e.target.value);
  };

  return (
    <form>
      <label for="pad">
        <span>Add your notes</span>
        <textarea
          rows="10"
          placeholder="Add notes here "
          name="pad"
          value={notes}
          onChange={handleChange}
        />
      </label>
    </form>
  );
}

工作示例https://codesandbox.io/s/still-moon-bmuof


推荐阅读