这可能是一个noob问题,但我面临着一些麻烦与useEffect()
钩.我有一个笔记应用程序,我想让数据持久化.我使用了2个useEffect
s:一个用于第一次刷新/加载页面时,另一个用于在我的应用程序中添加新注释时.
我放了一些日志(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)中,但随后会消失,只保留硬编码的数据:
它拨打的电话也比我预想的要多.你有什么 idea 吗?