【发布时间】:2022-01-17 18:50:20
【问题描述】:
我正在使用 NextJS,我正在尝试使用 localStorage 使状态保持不变,我是这样做的:
const [reportFavorite, setReportFavorite] = useState([
'captura',
'software',
'upload',
] as any)
useEffect(() => {
setReportFavorite(JSON.parse(window.localStorage.getItem('reportFavorite')))
}, [])
useEffect(() => {
window.localStorage.setItem('reportFavorite', reportFavorite)
}, [reportFavorite])
但 TypeScript 返回此错误:argument of type 'string | null' is not assignable to parameter of type 'string'
我在 StackOverflow 上阅读了一些答案,告诉我如果我这样做了:
useEffect(() => {
setReportFavorite(JSON.parse(window.localStorage.getItem('reportFavorite')!))
}, [])
使用!,它会修复它,但它没有,如果我这样做,我会收到另一个错误,说invalid character on line。
【问题讨论】:
标签: reactjs typescript next.js local-storage