【问题标题】:TypeScript errors in rootReducer and ActionrootReducer 和 Action 中的 TypeScript 错误
【发布时间】:2021-11-13 18:33:12
【问题描述】:

我正在做一个项目,显示来自 NASA 的 api 的图片,但出现了一些我不知道如何解决的错误。第一个在 store 的 index.ts 中,在 rootReducer 中,我在这里使用 combineReducers。 类型 'typeof PostsReducer' 不可分配给类型 'Reducer'

第二个是在发布操作中,Type 'AxiosResponse' 缺少来自 type 'Post[]' 的以下属性

这里是action和reducer:

import { createActionCreators } from "immer-reducer";

import { PostsReducer } from "../reducers/posts";
import { PostsRequestBody } from "../../api/main-protected";
import { AsyncAction } from "./common";

export const postsActions = createActionCreators(PostsReducer);

export type PostsActions = ReturnType<typeof postsActions.setPosts>;

export const getPosts =
  (body: PostsRequestBody): AsyncAction =>
  async (dispatch, _, { mainProtectedApi }) => {
    try {
      const posts = await mainProtectedApi.getPosts(body);
      console.log(posts);

      dispatch(postsActions.setPosts(posts));
    } catch (e) {
      console.log(e);
    }
  };

import { createReducerFunction, ImmerReducer } from "immer-reducer";

export interface Post {
  copyright: string;
  date: string;
  explanation: string;
  hdurl: string;
  media_type: string;
  service_version: string;
  title: string;
  url: string;
}

export interface PostsState {
  posts: Post[] | null;
}

const initialState: PostsState = {
  posts: null,
};

export class PostsReducer extends ImmerReducer<PostsState> {
  setPosts(posts: Post[]) {
    this.draftState.posts = posts;
  }
}

export default createReducerFunction(PostsReducer, initialState);
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import thunk from "redux-thunk";

import MainProtected from "../api/main-protected";
import { PostsActions } from "./actions/posts";
import { PostsReducer } from "./reducers/posts";

export const api = {
  mainProtectedApi: MainProtected.getInstance(),
};

declare global {
  interface Window {
    __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
  }
}

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const enhancer = composeEnhancers(
  applyMiddleware(thunk.withExtraArgument(api))
);

const rootReducer = combineReducers({
  PostsReducer,
});

export type State = ReturnType<typeof rootReducer>;
export type Actions = PostsActions;

export default createStore(rootReducer, enhancer);

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    所以,我解决了减速器的第一个问题。我正在导入由 createReducerFunction 创建的 PostsReducer 类,而不是 postsReducer。我通过更改导出解决了它:

    export const postsReducer = createReducerFunction(PostsReducer, initialState);
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2019-05-20
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2021-04-29
      • 2013-08-20
      相关资源
      最近更新 更多