如何在带有 TypeScript 的 redux 应用程序中使用选择器?

Sup*_*ver 6 typescript redux reselect

我尝试selectors在我的 Redux 应用程序中使用from reselect library。

我的选择器文件看起来:

import { createSelector } from 'reselect'

const postsSelectors = state => state.global.posts.allPostse;

export const getPosts = createSelector(
  [ postsSelectors ],
  (posts) => posts
);
Run Code Online (Sandbox Code Playgroud)

然后我尝试在我的组件中使用,如下所示:

const mapStateToProps = (state) => ({
  posts: getPosts(state),
});
Run Code Online (Sandbox Code Playgroud)

当我尝试编译所有这些时,出现以下错误:

在此处输入图片说明

我猜我是如何为 props 声明类型的,目前看起来是这样的:

interface Props{
 posts(state: any): any
 loadStories(): void;
};
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题。提前致谢。

Rad*_*io- 5

TypeScript 不需要第一个参数的数组。只需将您的选择器函数作为参数传递给 createSelector,如

export const getPosts = createSelector(
  postsSelectors,
  (posts) => posts
);
Run Code Online (Sandbox Code Playgroud)


小智 5

更多类型的示例:

  1. 描述类型
type TPostData = {
  type: string;
};

type TPostsState = TPostData[];

type TState = {
  posts: TPostsState;
};
Run Code Online (Sandbox Code Playgroud)
  1. 创建选择器
// get all posts
export const selectPosts = (state: TState): TPostsState => state.posts;

// get new posts
export const selectNewPosts = createSelector<
  TState,
  TPostsState,
  TPostData[]>(
    selectPosts,
    (posts) => posts.filter(({ type }) => type === 'new'),
  );
Run Code Online (Sandbox Code Playgroud)

结果:您已获得所有类型参数为“new”的帖子。


归档时间:

查看次数:

11878 次

最近记录:

5 年,5 月 前