简体   繁体   English

如何在页面重新加载时从 localStorage 获取数据

[英]how to get data from localStorage on page reload

I'm trying to make a savable note with React and localStorage.我正在尝试使用 React 和 localStorage 做一个可保存的笔记。 Whenever ' Save ' is clicked, it should save the value in the textarea to localStorage , and whenever ' Clear ' is clicked, it should clear the textarea and the data from localStorage .每当点击 ' Save ' 时,它应该textarea 中的值保存localStorage ,并且每当点击 ' Clear ' 时,它应该清除 textarealocalStorage 中的数据。

import { useState } from "react";
import "./App.css";

function App() {
  const storage = window.localStorage;
  const [text, setText] = useState('');
  const data = storage.getItem('text');

  return (
    <div className="App">
      <div className="box">
        <div className="field">
          <div className="control">
            <textarea
              className="textarea is-large"
              placeholder="Notes..."
              value={data}
              onChange={(e) => setText(e.target.value)} />
          </div>
        </div>
        <button
          className="button is-large is-primary is-active"
          onClick={() => storage.setItem('text', text)}>Save</button>
        <button
          className="button is-large"
          onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
      </div>
    </div>
  );
}

export default App;

It works as supposed, except, when I click 'save' , I can't type or delete anything in the textarea.它按预期工作,除了当我单击'save' 时,我无法在 textarea 中键入或删除任何内容。 Also, when I click 'clear' it clears the box only after I reload the page.此外,当我单击“清除”时,它仅在我重新加载页面后才清除该框。

How can I fix this?我怎样才能解决这个问题?

First, you should set the value of the textarea using the state variable text , otherwise you cannot edit it anymore once you click save.首先,您应该使用状态变量text设置 textarea 的值,否则一旦单击保存就无法再编辑它。 This is because the value on the local storage stays the same when you type, thus making it impossible to update the value.这是因为本地存储上的值在您键入时保持不变,因此无法更新该值。

Second, you need to initialize the state variable text to the value that you have in the local storage if there is any.其次,您需要将状态变量text初始化为本地存储中的值(如果有)。 Otherwise, it will always be empty when you refresh.否则,刷新时它将始终为空。

The code to apply both of these changes is the following:应用这两项更改的代码如下:

function App() {
  const storage = window.localStorage;
  const data = storage.getItem('text');
  const [text, setText] = useState(data ?? '');

  return (
    <div className="App">
      <div className="box">
        <div className="field">
          <div className="control">
            <textarea
              className="textarea is-large"
              placeholder="Notes..."
              value={text}
              onChange={(e) => setText(e.target.value)} />
          </div>
        </div>
        <button
          className="button is-large is-primary is-active"
          onClick={() => storage.setItem('text', text)}>Save</button>
        <button
          className="button is-large"
          onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
      </div>
    </div>
  );
}

export default App;

In the textArea element you have to assign the "value" as your "text" state.textArea元素中,您必须将“值”分配为“文本”状态。

<textarea
     className="textarea is-large"
     placeholder="Notes..."
     value={text} // --> here
     onChange={(e) => setText(e.target.value)} />

See here: Working example请参阅此处: 工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM