【问题标题】:Displaying local storage values in a text-area with react-hooks使用 react-hooks 在文本区域中显示本地存储值
【发布时间】:2020-04-16 07:46:05
【问题描述】:

我正在尝试在 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>
)

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    将 textarea valuenotes 变量一起使用。 对于此示例,您不需要 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

    【讨论】:

    • 完美,因为占位符在显示注释之前不会在渲染时闪烁。谢谢。
    【解决方案2】:

    1) 您应该将notes 状态绑定到TextArea 的值属性。

    2) 您需要添加一个空数组作为useEffect 钩子的依赖数组,以便其中的方法在组件渲染时只运行一次。这将确保在安装组件时使用来自localStorage 的值更新状态。

    const [notes, setNotes] = useState("")
    
    useEffect(() => {
      const notes = localStorage.getItem("notes")
      if (notes) {
        setNotes(notes)
      }
    }, [])
    
    const handleChange = e => {
      const { value } = target
      setNotes(e.target.value)
      localStorage.setItem("notes", value))
    }
    
    return (
      <form>
        <label for="pad">
          <span>Add your notes</span>
          <textarea
            rows="10"
            placeholder="Add notes here ?"
            name="pad"
            onChange={handleChange}
            value={notes}
          ></textarea>
        </label>
      </form>
    )
    

    【讨论】:

    • JSON.stringifyJSON.parse 对于 textarea 已经是字符串的值没有意义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多