是否可以为 useSelector 创建一个可重用的函数?

Is it possible to create a reusable function for useSelector?

我很好奇是否有办法在 redux 中重用 useSelector,因为我在不同的屏幕上多次使用它。

我试过像这样创建一个 selector.ts 文件,但它没有用,因为它不在商店内,也不是功能组件。知道如何重用此代码吗?

export const branch = useSelector((state: any) => state.branchReducer.branch);

您可以将选择器函数粘贴到文件中,然后让每个组件导入选择器并将其传递给 useSelector:

// selectors.ts
export const branchSelector = (state: any) => state.branchReducer.branch;

// used like:
import { branchSelector } from './some/path'
const Example = (props) => {
  const branch = useSelector(branchSelector);
  // ...
}

或者您可以创建自定义挂钩并使用它们:

// selectorHooks.ts
export const useBranch = () => useSelector((state: any) => state.branchReducer.branch);

// used like:
import { useBranch } from './some/path';
const Example = (props) => {
  const branch = useBranch();
  // ...
}