redux 使用“插件”-创建自定义“useAppStore”:哪种方法更好?[关闭]

ippsafx7  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(155)

已关闭。此问题为opinion-based。目前不接受回答。
**要改进此问题吗?**更新此问题,以便editing this post可以使用事实和引文来回答。

25天前关闭
Improve this question
这是我创建选择器的代码

import { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'Store/InjectorsTypes';
import { initialState } from 'Slice/DocumentHubSlice';

const selectDomain = (state: RootState) => state?.documentHub || initialState;

export const selectDocuments = createSelector(
  [selectDomain],
  (state) => state.documents,
);

export const selectUploadedDocuments = createSelector(
  [selectDomain],
  (state) => state.uploadedDocuments,
);

export const selectDocumentsLoading = createSelector(
  [selectDomain],
  (state) => state.documentsLoading,
);

export const selectDocumentsLoaded = createSelector(
  [selectDomain],
  (state) => state.documentsLoaded,
);

export const selectDocumentsEnded = createSelector(
  [selectDomain],
  (state) => state.documentsEnded,
);

export const selectSort = createSelector(
  [selectDomain],
  (state) => state.sort,
);

export const selectCompanyName = createSelector(
  [selectDomain],
  (state) => state.companyName,
);

export const selectCompanyLogo = createSelector(
  [selectDomain],
  (state) => state.companyLogo,
);

export const selectChatGptAllowed = createSelector(
  [selectDomain],
  (state) => state.chatgptAllowed,
);

export const selectDrawerOpen = createSelector(
  [selectDomain],
  (state) => state.drawerOpen,
);

export const selectUploading = createSelector(
  [selectDomain],
  (state) => state.uploading,
);

export const selectDownloading = createSelector(
  [selectDomain],
  (state) => state.downloading,
);

export const selectDeleting = createSelector(
  [selectDomain],
  (state) => state.deleteing,
);

export const selectDownloadUrl = createSelector(
  [selectDomain],
  (state) => state.downloadUrl,
);

字符串
然而,我可以看到太多的冗余。我想用我的这段代码替换上面的代码

import { useSelector } from 'react-redux';
import { RootState } from 'Store/InjectorsTypes';
import { initialState } from 'Slice/DocumentHubSlice';

export function useAppSelector<T>(selector: (state: RootState) => T) {
  return useSelector((state: RootState) => selector(state) || initialState);
}


有了这个自定义钩子,我可以像这样在我的组件中使用它

const documents = useAppSelector((state) => state.documentHub.documents);
const uploadedDocuments = useAppSelector((state) => state.documentHub.uploadedDocuments);
// ... and so on


我想知道第二种方法是否比第一种方法更好。我应该用第二种方法替换我的初始代码吗?

8fq7wneg

8fq7wneg1#

一般来说,你应该始终使用Redux Toolkit的“TypeScript快速入门”指南中所示的useAppSelector,无论你是否使用createSelector
除此之外,对于你给出的任何例子,你可能都不需要 * createSelector,只要这些选择器不做任何有意义的(昂贵的)计算或创建新对象-在这两种情况下,你应该总是使用记忆选择器。
但使用它们也无妨--所以这取决于你。
PS:那个|| initialState真的很奇怪--你总是在那里有一个状态,所以为什么要加上这个呢?

相关问题