Issue
该问题是由以下原因引起的useEffect
以及您最初如何设置状态:
useEffect(() => {
localStorage.setItem('react-notes', JSON.stringify(notes));
console.log('new note call:', notes)
}, [notes])
以上useEffect
每次都运行notes
变化,还要挂载。并且在安装时状态等于给定的初始数组useState
。所以localStorage
设置为该数组。
Solution
解决方案是更改设置状态的方式,如下所示,以便您选择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"))
);