【问题标题】:Define react redux state with typescript用 typescript 定义 react redux 状态
【发布时间】:2021-10-22 12:03:38
【问题描述】:

我有这样的 todoReducer.ts 文件

import ActionType from "../types";

const initialState = {
  items: [],
};

interface Item {
  task: string;
  priority: string;
  id: string;
  isActive: boolean;
  label: string;
}

function reducer(state = initialState, action: any) {
  switch (action.type) {
    case ActionType.ADD_ITEM:
      return { ...state, items: [action.payload, ...state.items] };

    case ActionType.CROSS_ITEM:
      return {
        ...state,
        items: state.items.map((e: Item) => {
          if (e.id === action.payload) e.isActive = false;
          return e;
        }),
      };

    default:
      return state;
  }
}
export default reducer;

然后根reducer这样

import { combineReducers } from "redux";
import authReducer from "./authReducer";
import todoReducer from "./todoReducer";

const reducers = combineReducers({
  auth: authReducer,
  todo: todoReducer,
});

export default reducers;

export type State = ReturnType<typeof reducers>;

在我的 todoList.jsx 文件中

    import {State} from "../store/reducers/index"
    const TodoList = ()=>{
     const items = useSelector((state:State) => state.todo.items);
...

    }

这给了我一个错误

“从不”类型上不存在属性“项目”。

似乎 initialState 的 items 对象无法被 ts 识别。

我该如何解决这个问题?

更新 在评论之后,我添加了

export type State = ReturnType<typeof store.getState>;

但我将鼠标悬停在 store.getState 上,它说同样的错误。我认为它仍然没有选择类型

【问题讨论】:

    标签: reactjs typescript vue.js react-redux


    【解决方案1】:

    createStore时应该声明类型

    const store = createStore(reducers, ...)
    export type State = ReturnType<typeof store.getState>;
    

    【讨论】:

    • 嗨更新问题我认为那个地方也行不通
    【解决方案2】:

    你应该在创建reducer时更新initialState的typw

    const initialState: Array<Item > = {
      items: [],
    };
    

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2018-07-23
      • 2021-12-09
      • 1970-01-01
      • 2020-09-21
      • 2021-08-04
      • 2021-01-24
      • 2018-05-01
      • 2018-12-31
      相关资源
      最近更新 更多