首页 > 解决方案 > React-Redux,LocalStorage:TypeScript 错误同时保存数据

问题描述

我正在学习React-ReduxTypeScript
在我的小应用程序中,我想使用localStorage在本地保存数据。我试图根据这个答案解决它,但遇到了打字稿错误。我试图将 type any定义为临时解决方案,但没有帮助。

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'

由于有 2 个动作reducers,我不得不使用combineReducers。对于副作用,我正在使用thunk middleware。我认为store是保存数据的正确组件。
任何帮助表示赞赏

rootReducer.ts

import { combineReducers } from 'redux'
import carReducer from './Car/CarReducer'
import ProductReducer from "./Products/ProductReducer"

const rootReducer = combineReducers({
     car: carReducer,
    products: ProductReducer
})

export default rootReducer

store.ts

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

import RootReducer from './RootReducer'

 const persistedState = localStorage.getItem('state') ?
 JSON.parse(localStorage.getItem('state')) : {} // <--- typescript  error here 
 
const store = createStore(
  RootReducer,
  persistedState,
  composeWithDevTools(applyMiddleware(thunk))
)

store.subscribe(()=>{
  localStorage.setItem('reduxState', JSON.stringify(store.getState())) 
}) 

export default store

标签: reactjstypescriptreact-reduxlocal-storage

解决方案


Typescript 无法知道getItem多次调用会导致每次返回相同的内容。因此,当您使用返回的第一个值检查 null 时,这对第二个值没有影响。

解决方法是只调用一次,并将结果保存到变量中:

const temp = localStorage.getItem('state');
const persistedState = temp ? JSON.parse(temp) : {};

推荐阅读