Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React-Redux,LocalStorage:以LCO方式保存数据时发生类型脚本错误_Reactjs_Typescript_React Redux_Local Storage - Fatal编程技术网

Reactjs React-Redux,LocalStorage:以LCO方式保存数据时发生类型脚本错误

Reactjs React-Redux,LocalStorage:以LCO方式保存数据时发生类型脚本错误,reactjs,typescript,react-redux,local-storage,Reactjs,Typescript,React Redux,Local Storage,我正在学习React Redux和TypeScript 在我的小应用程序中,我想使用localStorage在本地保存数据。 我试图根据解决它,但遇到了一个typescript错误。我试图将typeany定义为一个临时解决方案,但没有任何帮助 Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'strin

我正在学习React Redux和TypeScript
在我的小应用程序中,我想使用localStorage在本地保存数据。 我试图根据解决它,但遇到了一个typescript错误。我试图将typeany定义为一个临时解决方案,但没有任何帮助

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

由于有两个操作减速机,我不得不使用组合减速机。对于副作用,我正在使用thunk中间件。 我假设store是保存数据的正确组件
谢谢你的帮助

根还原剂

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

从'redux'导入{createStore,applyMiddleware}
从'redux devtools extension'导入{composeWithDevTools}
从“redux thunk”导入thunk
从“./RootReducer”导入RootReducer
const persistedState=localStorage.getItem('state')?
parse(localStorage.getItem('state')):{}//{
localStorage.setItem('reduxState',JSON.stringify(store.getState()))
}) 
导出默认存储

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

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

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

@谢谢你的回答。它解决了打字问题。我的代码中是否缺少任何内容,或者是否应该添加任何功能以在本地保存数据。我选中了,当我刷新页面时,没有保存任何内容,但在devtools中的应用程序中,我看到一个键“reduxState”,并为添加到篮子中的一个产品赋值。在代码片段中,设置时使用
“reduxState”
,而获取时使用
“state”
。它们必须是一样的。@Nicholas Tower非常感谢你。你救了我:)