【问题标题】:Imports not working with typescript reducer in redux导入不适用于 redux 中的 typescript reducer
【发布时间】:2021-12-27 21:23:59
【问题描述】:

我正在尝试将 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'.

【问题讨论】:

  • 您不是真的打算export const allReducers 并在createStore 中使用它吗?而不是通过typeallReducers?
  • 我实际上不确定我对 typescript 很陌生,并试图在商店中使用 typescript 我应该如何编写它

标签: reactjs typescript redux react-redux local-storage


【解决方案1】:

我对 redux 没有太多经验,但是通过阅读 the documentation of createStore,我发现:

createStore​

Redux 的 createStore。您应该不需要直接使用它。

查看createStore 的参数时,this documentation 表示第一个参数应该是 reducing function,在这里您传递的是导出的打字稿类型,而不是实际可调用的函数。 这使我相信您错误地使用了createStore,这可以解释您的错误:Attempted import error: 'RootState' is not exported from '../reducers/index'.

我将从Typescript Quick Start 开始,并使用configureStore,因为他们建议设置RootState

另见:

可以在React & Redux in TypeScript - Complete Guide:Store Configuration 上找到稍微不同且更高级的用法(如果需要的话),但我仍会从基本教程开始,然后从那里开始工作。

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2022-01-22
    • 2020-06-28
    • 2018-06-05
    相关资源
    最近更新 更多