Reactjs - createStore не может распознать редуктор при использовании машинописи - PullRequest
0 голосов
/ 26 апреля 2020

Я новичок в Reactjs и Typescript, но попытался написать проект элемента todo. но когда я вызвал createStore, я получил ошибку в VSCode, и я не могу разрешить.

Любая помощь будет высоко ценится.

index.tsx

...
import { Provider } from "react-redux";
import { createStore } from "redux";
import itemReducer from "./reducers/itemReducer";

const store = createStore(itemReducer);
...

itemReducer.ts

...
export const ActionType = {
  INIT_ITEM : "INIT_ITEM",
  ADD_ITEM : "ADD_ITEM",
  EDIT_ITEM : "EDIT_ITEM",
  DEL_ITEM : "DEL_ITEM"
}


export interface Reduce_State {
  items: Todo_Item[];
}

export interface Reduce_Action {
  type: string;
  item: Todo_Item;
  items: Todo_Item[];
  itemIndex: number;
}


export default function itemReducer(state: Reduce_State, action: Reduce_Action) {
  if (!state) {
    state = {
      items: [],
    };
  }

  switch (action.type) {
    case ActionType.INIT_ITEM:
      return { items: action.items };
    default:
      return state;
}
...

, когда я переместил мышь на itemReducer, VSCode подсказал мне

(alias) function itemReducer(state: Reduce_State, action: Reduce_Action): Reduce_State
import itemReducer
No overload matches this call.
  Overload 1 of 2, '(reducer: Reducer<Reduce_State, Reduce_Action>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<Reduce_State, Reduce_Action>', gave the following error.
    Argument of type '(state: Reduce_State, action: Reduce_Action) => Reduce_State' is not assignable to parameter of type 'Reducer<Reduce_State, Reduce_Action>'.
  Overload 2 of 2, '(reducer: Reducer<Reduce_State, Reduce_Action>, preloadedState?: { items: { key: string; content: string; completed: boolean; editing: boolean; }[]; } | undefined, enhancer?: StoreEnhancer<...> | undefined): Store<...>', gave the following error.
    Argument of type '(state: Reduce_State, action: Reduce_Action) => Reduce_State' is not assignable to parameter of type 'Reducer<Reduce_State, Reduce_Action>'.ts(2769)
Peek Problem (Alt+F8)
No quick fixes available

enter image description here

и когда я переместил мышь на createStore, я получил сообщение:

(alias) createStore<Reduce_State, Reduce_Action, unknown, unknown>(reducer: Reducer<Reduce_State, Reduce_Action>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<...> (+1 overload)
import createStore

enter image description here

1 Ответ

0 голосов
/ 26 апреля 2020

Судя по вашему сообщению об ошибке у вас несоответствие типов. Лично я не знаю решения для одного редуктора, но мне подходит использование функции ОбъединитьReducers . Функция combReducers даст вам тип возвращаемого значения, который вам нужен для функции createStore, и позволит вам использовать несколько редукторов.

const rootReducer = combineReducers({
   itemState: itemReducer
})

Потому что было неудобно использовать React с TS и Redux, когда перехватывает не были мейнстримом, я сделал репо, чтобы помочь людям с проблемами, связанными с этим топи c. Мэйби, это тебе поможет.

https://github.com/iamnepster/react-ts-redux-todolist

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...