我正在学习React Redux和TypeScript
在我的小型应用程序中,我想使用localStorage在本地保存数据。我试图根据这个答案解决它,但遇到了一个打字错误。我试图将any类型定义为临时解决方案,但无济于事。
Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'
由于有两个动作,减速器我不得不使用组合减速器。对于副作用,我使用thunk中间件。我认为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
存储.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
Typescript无法知道多次调用getItem
会导致每次返回相同的内容。因此,当您使用返回的第一个值检查null时,这与第二个值没有区别。
修复方法是只调用一次,并将结果保存到一个变量:
const temp = localStorage.getItem('state');
const persistedState = temp ? JSON.parse(temp) : {};