useState 和 localStorage:'string null' 类型的参数不可分配给 'string' 类型的参数

useState and localStorage: argument of type 'string null' is not assignable to parameter of type 'string'

我正在使用 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 returns 这个错误:argument of type 'string | null' is not assignable to parameter of type 'string'

我在 Whosebug 上阅读了一些答案,告诉我如果我这样做了:

useEffect(() => {
    setReportFavorite(JSON.parse(window.localStorage.getItem('reportFavorite')!))
  }, [])

使用 !,它会修复它,但它没有,如果我这样做,我会收到另一个错误提示 invalid character on line

试试这个:

const [reportFavorite, setReportFavorite] = useState([
    'captura',
    'software',
    'upload',
  ] as any)

  useEffect(() => {
    const reportFavouriteInStorage = localStorage.getItem('reportFavorite');
    if(!!reportFavouriteInStorage){
      setReportFavorite(JSON.parse(reportFavouriteInStorage))
    }
  }, [])

  useEffect(() => {
    localStorage.setItem('reportFavorite', reportFavorite)
  }, [reportFavorite])