这可能是一个noob问题,但我面临着一些麻烦与useEffect()钩.我有一个笔记应用程序,我想让数据持久化.我使用了2个useEffects:一个用于第一次刷新/加载页面时,另一个用于在我的应用程序中添加新注释时.

我放了一些日志(log)来判断发生了什么:

const [notes, setNotes] = useState([
  {
  noteId: nanoid(),
  text: 'This is my 1st note!',
  date: '30/07/2022'
  },
  {
    noteId: nanoid(),
    text: 'This is my 2nd note!',
    date: '30/07/2022'
  }
])

// 1st time the app runs
useEffect(() => {
  const savedNotes = JSON.parse(localStorage.getItem('react-notes'))
  console.log('refresh page call:',savedNotes)

  if(savedNotes) {
    setNotes(savedNotes)
  }
}, [])

//every time a new note is added
useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

这种行为有点奇怪,因为刷新页面时,新数据会出现在日志(log)中,但随后会消失,只保留硬编码的数据:

enter image description here

它拨打的电话也比我预想的要多.你有什么 idea 吗?

推荐答案

Issue

问题是由以下useEffect以及您最初如何设置状态引起的:

useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

每当notes次更改时,上述useEffect次都会运行,但也会在mount上运行.在挂载时,状态等于给定给useState的初始array.因此localStorage被设置为该array.

Solution

一种解决方案是改变设置状态的方式,如下所示,因此如果有什么,请 Select localStroge中的内容,否则使用您拥有的初始数组:

const [notes, setNotes] = useState(
  !localStorage.getItem("react-notes")
    ? [
        {
          noteId: nanoid(),
          text: "This is my 1st note!",
          date: "30/07/2022",
        },
        {
          noteId: nanoid(),
          text: "This is my 2nd note!",
          date: "30/07/2022",
        },
      ]
    : JSON.parse(localStorage.getItem("react-notes"))
);

Javascript相关问答推荐

如何为GrapesJS模板编辑器创建自定义撤销/重复按钮?

zoom svg以适应圆

在页面上滚动 timeshift 动垂直滚动条

基于变量切换隐藏文本

微软Edge编辑和重新发送未显示""

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

用于编辑CSS样式的Java脚本

Angular 中的类型错误上不存在获取属性

Reaction Native中的范围滑块

为什么123[';toString';].long返回1?

在forEach循环中获取目标而不是父对象的属性

本地库中的chartjs-4.4.2和chartjs-plugin-注解

从Nextjs中的 Select 项收集值,但当单击以处理时,未发生任何情况

Puppeteer上每页的useProxy返回的不是函数/构造函数

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

使用插件构建包含chart.js提供程序的Angular 库?

每次重新呈现时调用useState initialValue函数

Phaser3 preFX addGlow不支持zoom

无法使用Redux异步函数读取未定义的useEffect钩子的属性';map';

如何在加载页面时使锚定标记成为焦点