reactjs - React-Redux,LocalStorage:TypeScript 错误同时保存数据
问题描述
我正在学习React-Redux和TypeScript。
在我的小应用程序中,我想使用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
解决方案
Typescript 无法知道getItem
多次调用会导致每次返回相同的内容。因此,当您使用返回的第一个值检查 null 时,这对第二个值没有影响。
解决方法是只调用一次,并将结果保存到变量中:
const temp = localStorage.getItem('state');
const persistedState = temp ? JSON.parse(temp) : {};
推荐阅读
- python - 更新 numpy.ndarray 中的值
- python - 如何在 beautifulsoup 中刮取 image-src
- mapping - 将不兼容的属性从 DTO 映射到实体
- rest - 如何正确创建自定义 REST API 端点
- javascript - 执行前如何在另一个键中调用对象属性
- bash - bash 遍历文件夹中的文件,并在文件夹中有新文件时更新循环
- sequelize.js - 当内部连接为空时如何更新 res?
- javascript - 获取运行时默认语言环境的 JavaScript 标准 API?
- python - 有没有办法使用 Python 和 BeautifulSoup 收集城市中特定特许经营权的 Yelp 页面的所有 URL?
- vue.js - 向 vee 验证器添加自定义错误(ErrorBag)