首页 > 解决方案 > 导入不适用于 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'.

标签: reactjstypescriptreduxreact-reduxlocal-storage

解决方案


我对 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上找到稍微不同和更高级的用法(如果需要的话),但我仍然会从基本教程开始并从那里开始工作。


推荐阅读