reactjs - 导入不适用于 redux 中的 typescript reducer
问题描述
我正在尝试将 redux 与 typescript 一起使用,并将状态保存到本地存储中,但我在保存状态时遇到了一些困难,这是我当前的代码。我是键入脚本的新手,有人有什么建议吗
减速机
import { combineReducers } from "redux";
import user from "./user";
import account from "./account";
const allReducers = combineReducers({
user:user
account:account
});
export type RootState = ReturnType<typeof allReducers>
store.js
import { createStore } from "redux";
import {RootState} from '../reducers/index'
function saveToLocalStorage(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem("state", serializedState);
} catch (e) {
console.log(e);
}
}
function loadFromLocalStorage() {
try {
const serializedState = localStorage.getItem("state");
if (serializedState == null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (e) {
console.log(e);
return undefined;
}
}
const savedState = loadFromLocalStorage();
const store = createStore(
RootState,
savedState,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
store.subscribe(() => saveToLocalStorage(store.getState()));
export default store;
当我尝试编译代码时,我不断收到此错误。
Attempted import error: 'RootState' is not exported from '../reducers/index'.
解决方案
我对 redux 没有太多经验,但是通过阅读的文档createStore
,我发现:
创建商店</h1>
Redux 的 createStore。您不需要直接使用它。
在查看 的参数时createStore
,该文档说第一个参数应该是
reduce function,而在这里您传递的是导出的 typescript 类型而不是实际可调用的函数。这使我相信您使用createStore
不正确,这可以解释您的错误:Attempted import error: 'RootState' is not exported from '../reducers/index'.
我将从Typescript 快速入门开始,并configureStore
按照他们的建议使用RootState
.
另见:
可以在 TypeScript - Complete Guide : Store Configuration的React 和 Redux上找到稍微不同和更高级的用法(如果需要的话),但我仍然会从基本教程开始并从那里开始工作。
推荐阅读
- java - 如何修复 Spring Boot Kotlin 项目中的“未解决的参考:java”?
- python - 使用 xlrd 在 Excel 中读取特殊字符
- android - 如何在 JSONArray 中获取包含 6000 多个对象的 JSON API 响应
- android - 如何在 Espresso 中对视图执行多次点击
- react-native - React Native - 在滚动视图上的视图中禁用滚动拖动检测(类似于停止传播)
- python-3.x - 当我在此按钮上添加图像时,Tkinter 按钮不起作用
- angular - 验证密码和确认密码
- java - 为什么使用 apache-email 库时附件文件名损坏?
- robotframework - 如何根据文本选择复选框
- c# - 如何修补已签名的 dll