【问题标题】:useState and localStorage: argument of type 'string null' is not assignable to parameter of type 'string'useState 和 localStorage:“string null”类型的参数不能分配给“string”类型的参数
【发布时间】: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


    【解决方案1】:

    试试这个:

    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])
    

    【讨论】:

    • 我遇到了与尝试使用“!”时相同的错误,说无效字符:i.imgur.com/4vLZS23.png
    • 如果你只删除 JSON.parse 会怎样?
    • 你能用你的完整组件更新你的问题吗?
    • 它可以在没有 JSON.parse 的情况下工作,你是对的。我只是在使用布尔值 useState 时遇到了麻烦。在 localStorage 上它总是设置为 false。但我设法绕过它。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2021-10-02
    • 2021-09-30
    • 2021-10-06
    • 2020-04-15
    • 2021-09-06
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多